<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

/**
 * 民宿2期 接口地址 2021-07-10 开始编写
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $mainhost = "";
    protected $mhotel = "";
    protected $mhouse = "";
    protected $muser = "";

    public function __construct(){
        parent::__construct();
        $this->mainhost = "http://".$_SERVER["HTTP_HOST"];
        $this->mhotel = model("hotels");
        $this->mhouse = model("house");
        $this->muser = model("user");
        $this->morder = model("order");
    }

    /**
     * 首页
     *
     */
    public function index()
    {
        $this->success('请求成功');
    }

    //关于我们图片
    public function aboutimg(){
        $imgurl = "https://yunzhuke.net/aboutus.jpg";
        $this->success("success",$imgurl);
    }

    //入驻申请信息显示
    public function getApplyInfo(){
        $info = db("apply")->where(['id'=>1])->field("content")->find();
        if($info && $info['content']){
            $this->success("success",$info);
        }else{
            $this->error("数据错误");
        }
    }

    //提交房屋申请数据
    public function applydata(){
        $data['username'] = $this->request->request("nickName");
        $data['phone'] = $this->request->request("phone");
        $data['province'] = $this->request->request("province");
        $data['city'] = $this->request->request("city");
        $data['area'] = $this->request->request("area");
        $data['size'] = $this->request->request("size");
        $data['count'] = $this->request->request("count");
        $data['address'] = $this->request->request("address");
        $data['stage'] = $this->request->request("stage");
        $data['stage2'] = $this->request->request("stage2");
        $now = time();
        $data['createtime'] = $now;
        $data['updtime'] = $now;

        $inid = db("apply")->insertGetId($data);
        if($inid){
            $this->success("提交成功");
        }else{
            $this->error("提示失败");
        }

    }

    /**
     * @return array
     */
    public function getNoNeedLogin()
    {
        return $this->noNeedLogin;
    }


    //获取酒店下可以出租的房源 以推荐排序 id 次之
    protected function getHrooms($hid){

        $list = $this->mhouse
            ->where("auditing = 1")
            ->where("h_id={$hid}")
            ->field('id as roomid,h_title as roomtitle,h_hot as roomhot,h_price as roomprice,h_attr as roomattr,concat("'.$this->mainhost.'", h_img) as roomimg')
            ->order("h_hot desc,id asc")
            ->select();
        return $list;
    }

    //获取酒店可预订的房间数量
    protected function getHRcount($hid){
        $count = $this->mhouse->where(['h_id'=>$hid,'h_status'=>'normal'])->count();
        return $count;
    }

    //首页地图 获取酒店数据和可预订房间数量 考虑到性能 当用户点击具体酒店后 再请求接口给出房源数据
    public function getHotels(){
        $citycode = $this->request->request("citycode");
        $title = $this->request->request("title");
        if(empty($citycode)){
            $this->error('参数错误');
        }
        if($title){
            $list = $this->mhotel->where("h_status='normal'")->where(['h_areadid'=>$citycode])->where("`hoteltitle` LIKE '%$title%'")->field("hid as id,hoteltitle as name,h_address as address,lng,lat")->select();
        }else{
            $list = $this->mhotel->where("h_status='normal'")->where(['h_areadid'=>$citycode])->field("hid as id,hoteltitle as name,h_address as address,lng,lat")->select();
        }


        if($list){
            foreach ($list as $k=>&$v){
                //获取酒店房源
                $v["count"] = $this->getHRcount($v["id"]);
            }
            $this->success("success",$list);
        }else{
            $this->success("暂无酒店数据",[]);
        }
    }

    //首页点击锚点获取酒店详情
    public function getIdetail(){
        $hid = $this->request->request("hid");
        $lng1 = $this->request->request("lng");
        $lat1 = $this->request->request("lat");
        $uid = $this->request->request("uid",0);
        if(empty($hid)){
            $this->error('参数错误');
        }
        if(empty($lng1) || empty($lat1)){
            $this->error('经纬度参数错误');
        }

        $distance = 0;
        //平分等级 目前只考虑整数 评论分 1一般 2 普通 3 很好 4 推荐 5 超棒
        $pointer = [
            "1"=>'一般',
            "2"=>'普通',
            "3"=>'很好',
            "4"=>'推荐',
            "5"=>'超棒',
        ];

        $lbs = db("label");
        $tps = db("type");
        $clc = db("collect");

        $res = [];
        $hotel = $this->mhotel->where(['hid'=>$hid])->field("hid,lng,lat,h_point,h_img,hoteltitle,h_types")->find();

        if($hotel){
            $distance = getdistancekm($lng1,$lat1,$hotel["lng"],$hotel["lat"]);
            $res['distance'] = "距离定位位置".$distance."km";
            $res['h_img'] =  $this->mainhost.$hotel["h_img"];
            $res['h_pointname'] = $pointer[$hotel['h_point']];
            $res['h_point'] = sprintf("%1\$.1f",$hotel["h_point"]);//保留一位小数
            //最近预定 随机
            //时间
            $res['min'] = mt_rand(10,40)."分钟前有人预定";//随机一个两位数
            //判断是否收藏
            if($uid){
                $has = $clc->where(['uid'=>$uid,'hid'=>$hid])->find();
                if($has){
                    $res['collect'] = 1;
                }else{
                    $res['collect'] = 0;
                }
            }else{
                $res['collect'] = 0;
            }
            $types = [];
            $labels = [];
            $price = 0;
            $rid = 0;
            //取出房间价格最小的一个房间的信息   属性 标签 价格
            $info = db("house")->where(['h_id'=>$hid,'h_status'=>'normal','h_statusText'=>'normal'])->field("id,h_id,h_price,h_types,h_lebals")->order("h_price asc")->find();
            if($info){
                //房型
                $type = $hotel["h_types"];
                $typearr = $tps->where("id in ($type)")->field("ttitle")->select();
                if($typearr){
                    foreach ($typearr as $vv){
                        $types[] = $vv["ttitle"] ;
                    }
                }

                //标签
                $label = $info["h_lebals"];
                $labelarr = $lbs->where("id in ($label)")->field("ltitle")->select();
                if($labelarr){
                    foreach ($labelarr as $vv){
                        $labels[] = $vv["ltitle"] ;
                    }
                }
                //单价
                $price = $info['h_price'];
                $rid = $info['id'];
            }

            $res['text'] = "随时可住，2小时起租";
            $res['types'] = $types;
            $res['labels'] = $labels;
            $res['price'] = $price;
            $res['rid'] = $rid;
            $res['hid'] = $hid;


        }

        if($res){
            $this->success("success",$res);
        }else{
            $this->success("暂无数据",[]);
        }




    }

    //酒店筛选 包含： 商圈、关键词、地址、经纬度 等条件的搜索
    public function getHotelslist(){

        $lng1 = $this->request->request("lng");
        $lat1 = $this->request->request("lat");
        $citycode = $this->request->request("citycode");//城市编码
        $areaid = $this->request->request("areaid");//商圈
        $title = $this->request->request("title");//关键词
        $stime = $this->request->request("stime");
        $etime = $this->request->request("etime");

        if($stime){
            $stime0 = strtotime(date("Y-m-d",strtotime($stime)));
            $stime24 = strtotime(date("Y-m-d 23:59:59",strtotime($stime)));
        }
        $etime = $this->request->request("etime");

        if($etime){
            $etime0 = strtotime(date("Y-m-d",strtotime($etime)));
            $etime24 = strtotime(date("Y-m-d 23:59:59",strtotime($etime)));
        }

        if(empty($citycode)){
            $this->error('城市参数错误');
        }
        if(empty($lng1) || empty($lat1)){
            $this->error('经纬度参数错误');
        }

        if($areaid && $title){
            $list = $this->mhotel->where("h_status='normal'")->where("`hoteltitle` LIKE '%$title%'")->where(['h_areadid'=>$citycode])->where("FIND_IN_SET($areaid,`h_servs`)")->field("hid as id,hoteltitle as name,h_address as address,lng,lat,h_areadid as citycode,h_servs as areas")->select();
        }else if($areaid){
            $list = $this->mhotel->where("h_status='normal'")->where(['h_areadid'=>$citycode])->where("FIND_IN_SET($areaid,`h_servs`)")->field("hid as id,hoteltitle as name,h_address as address,lng,lat,h_areadid as citycode")->select();
        }else if($title){
            $list = $this->mhotel->where("h_status='normal'")->where(['h_areadid'=>$citycode])->where("`hoteltitle` LIKE '%$title%'")->field("hid as id,hoteltitle as name,h_address as address,lng,lat,h_areadid as citycode")->select();
        }else{
            $list = $this->mhotel->where("h_status='normal'")->where(['h_areadid'=>$citycode])->field("hid as id,hoteltitle as name,h_address as address,lng,lat,h_areadid as citycode")->select();
        }


        $templist = [];
        foreach ($list as $k=>&$v){
            $v["distance"] = getdistancekm($lng1,$lat1,$v["lng"],$v["lat"]);
            $sort[] = $v["distance"];
            $templist[$k] = $v;
        }

        if($templist){
            array_multisort($sort,SORT_ASC,$templist);

            foreach ($templist as $k=>&$vv){
                $closearr[] =[];
                $closestr = "";
                //处理逻辑 筛选出酒店下不能预定的房间id 排除这些 随机选择一个 即可
                //新增 排除 关闭的房间
                $olist = db("order")
                    ->where(["room_id"=>$vv['id']])
                    ->where("pay_status='1' || pay_status='2'")
                    ->where("stime >= '$stime0' && etime <= '$etime24' || etime >='$stime0' && stime <= '$stime0' || etime >= $stime0 && stime <= $etime24")
                    ->field("id,room_id,stime,etime,pay_status")
                    ->select();

                //关闭的房间数据
                $closelist = db("closeroom")
                    ->where(["chid"=>$vv['id']])
                    ->where("cstime >= '$stime0' && cetime2 <= '$etime24' || cetime2 >='$stime0' && cstime <= '$stime0' || cetime2 >= $stime0 && cstime <= $etime24")
                    ->field("crid")
                    ->select();


                if($closelist){
                    foreach ($closelist as $v){
                        $closearr[] = $v['crid'];
                        $closestr .=  $v['crid'].",";
                    }
                }

                if($olist){
                    foreach ($olist as $v){
                        $closearr[] = $v['room_id'];
                        $closestr .=  $v['room_id'].",";
                    }
                }

                if($closestr){
                    $closestr = rtrim($closestr,",");
                }

                if($closestr){
                    $info = db("house")
                        ->where(['h_id'=>$vv['id'],'h_status'=>'normal','h_statusText'=>'normal'])
                        ->where("id not in ($closestr)")
                        ->field("id")
                        ->order("h_price asc")
                        ->find();

                    if($info){
                        $vv['rid'] = $info["id"];
                    }else{
                        unset($templist[$k]);
                    }

                }else{
                    //取出房间价格最小的一个房间的信息   属性 标签 价格
                    $info = db("house")->where(['h_id'=>$vv['id'],'h_status'=>'normal','h_statusText'=>'normal'])->field("id")->order("h_price asc")->find();
                    $vv['rid'] = $info["id"];
                }

            }

            $resdata = [];
            foreach ($templist as $vd){
                $resdata[] = $vd;
            }

            $this->success("success",$resdata);
        }else{
            $this->success("暂无数据",[]);
        }

    }

    //首页地图点击锚点显示酒店房间列表
    public function getRoomlist(){
        $hid = $this->request->request("hid");
        $lng1 = $this->request->request("lng");
        $lat1 = $this->request->request("lat");
        $uid = $this->request->request("uid",0);

        if(empty($hid)){
            $this->error('参数错误');
        }
        if(empty($lng1) || empty($lat1)){
            $this->error('经纬度参数错误');
        }
        $distance = 0;
        $list = db("house")->where(['h_id'=>$hid,'h_status'=>'normal'])->field("id,h_title,h_img,h_price,h_types,h_lebals")->select();

        if($list){
            $hotel = $this->mhotel->where(['hid'=>$hid])->field("lng,lat")->find();
            //距离
            if($hotel){
                $distance = getdistancekm($lng1,$lat1,$hotel["lng"],$hotel["lat"]);
            }
            $lbs = db("label");
            $tps = db("type");
            $clc = db("collect");
            foreach ($list as $k=>&$v){
                $v["h_img"] = $this->mainhost.$v["h_img"];
                //标签
                $label = $v["h_lebals"];
                $labelarr = $lbs->where("id in ($label)")->field("ltitle")->select();
                if($labelarr){
                    foreach ($labelarr as $vv){
                        $v['h_label'][] = $vv["ltitle"] ;
                    }
                }else{
                    $v['h_label'] = [];
                }
                unset($v['h_lebals']);
                //房型
                $type = $v["h_types"];
                $typearr = $tps->where("id in ($type)")->field("ttitle")->select();
                if($typearr){
                    foreach ($typearr as $vv){
                        $v['h_type'][] = $vv["ttitle"] ;
                    }
                }else{
                    $v['h_type'] = [];
                }
                unset($v['h_types']);
                //距离
                $v['h_distance'] = $distance;
                //时间
                $v['min'] = mt_rand(10,40);//随机一个两位数
                //分数
                $v['point'] = mt_rand(3,5);//随机一个单位数
                //判断是否收藏
                if($uid){
                    $has = $clc->where(['uid'=>$uid,'rid'=>$v['id']])->find();
                    if($has){
                        $v['collect'] = 1;
                    }else{
                        $v['collect'] = 0;
                    }
                }else{
                    $v['collect'] = 0;
                }

                $sort[] = $v["point"];
            }

            array_multisort($sort,SORT_DESC,$list);

            $this->success("success",$list);
        }else{
            $this->error("暂无房源数据");
        }




    }

    //商圈列表
    public function getArea(){
        $citycode = $this->request->request("citycode");
        if(empty($citycode)){
            $this->error('参数错误');
        }
        $list = db("area")->where(['status'=>'normal'])->where(['citydid'=>$citycode])->field("id,atitle")->order("acount desc")->select();
        $this->success("success",$list);
    }

    //获取城市列表 只选择到 市级
    public function getCity(){
        $list = db("city")->where(['level'=>2])->field("areaId,areaCode,areaName,cityCode,center")->select();
        $this->success("success",$list);
    }

    //获取openid
    public function getOpenid()
    {

        $js_code = $this->request->request("code");
        $appid='wxd3ed1291e43598cd';
        $appSecret='3c112f9dced28d11507ea034efa3d099';
        $grant_type='authorization_code';
        $getUrl='https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$appSecret.'&js_code='.$js_code.'&grant_type='.$grant_type;

        $ch = curl_init();

        curl_setopt( $ch , CURLOPT_URL, $getUrl );
        curl_setopt( $ch , CURLOPT_HEADER, 0);

        curl_setopt( $ch , CURLOPT_RETURNTRANSFER, 1);
//        curl_setopt( $ch , CURL_SSLVERSION_SSL, 2);
        curl_setopt( $ch , CURLOPT_SSL_VERIFYPEER, FALSE);

        curl_setopt( $ch , CURLOPT_SSL_VERIFYHOST, FALSE);

        $data = curl_exec( $ch );
        $response = json_decode( $data );
        $a= $response ->openid;

        if($a){
            $this->success("获取成功",$a);
        }else{
            $this->error("openid获取失败");
        }

    }
    //微信授权登陆
    public function wxlogin(){
        $data['avatarUrl'] = $this->request->request("avatarUrl");
        $data['city'] = $this->request->request("city");
        $data['country'] = $this->request->request("country");
        $data['gender'] = $this->request->request("gender");
        $data['language'] = $this->request->request("language");
        $data['nickName'] = $this->request->request("nickName");
        $data['province'] = $this->request->request("province");

        $openid = $data['openid'] = $this->request->request("openid");
        if(empty($openid)){
            $this->error('openid参数错误');
        }
        $info = db('user')->where(["openid"=>$openid])->field("id,nickName,avatarUrl,phone")->find();
        if($info){
            $this->success("用户已经注册", $info);
        }else{
            //未注册
            $data["from"] = 1;
            $data['ctime'] = date('Y-m-d H:i:s', time());
            $data["group_id"] = 2;//默认用户组
            $id = db('user')->insertGetId($data);
            $res['id'] = $id;
            $res['nickName'] = $data['nickName'];
            $res['phone'] = "";
            $res['avatarUrl'] = $data['avatarUrl'];
            $this->success("注册成功", $data);
        }

    }

    //酒店房间去掉库存，以同类型房源处理，名字相同这代表是同类型
    public function getDetail(){
        $hdb = db("hotels");
        $rdb = db("house");
        $clc = db("collect");
        $cdb = db("comments");
        $catedb = db("category");
        $typedb = db("type");


        $hid = $this->request->request("hid");
        $rid = $this->request->request("rid");

        $uid = $this->request->request("uid");
        $stime = $this->request->request("stime");
        if($stime){
            $stime0 = strtotime(date("Y-m-d",strtotime($stime)));
            $stime24 = strtotime(date("Y-m-d 23:59:59",strtotime($stime)));
        }
        $etime = $this->request->request("etime");

        if($etime){
            $etime0 = strtotime(date("Y-m-d",strtotime($etime)));
            $etime24 = strtotime(date("Y-m-d 23:59:59",strtotime($etime)));
        }


        $ftype = $this->request->request("type",1);//0全日房 1 小时房

        if(empty($hid)){
            $this->error("hid不能为空");
        }
        if(empty($rid)){
            $this->error("rid不能为空");
        }
        if(empty($uid)){
            $this->error("uid不能为空");
        }
        if(empty($stime)){
            $this->error("开始时间不能为空");
        }
        if(empty($etime)){
            $this->error("结束时间不能为空");
        }

        $res = [];
        $w=date('w');

        //酒店入口
        if($hid){
            $hinfo = $hdb->where(['hid'=>$hid])->field("hid,hoteltitle,h_tel,h_address,h_content,h_imgs,lng,lat,h_guestroom,h_opentime,h_remodeltime")->find();
            $res['hotel']['hid'] = $hinfo['hid'];
            $res['hotel']['title'] = $hinfo['hoteltitle'];
            $res['hotel']['tel'] = $hinfo['h_tel'];
            $res['hotel']['address'] = $hinfo['h_address'];
            $res['hotel']['content'] = $hinfo['h_content'];
            $res['hotel']['lng'] = $hinfo['lng'];
            $res['hotel']['lat'] = $hinfo['lat'];
            $res['hotel']['guestroom'] = $hinfo['h_guestroom'];
            $res['hotel']['opentime'] = date("Y-m-d",strtotime($hinfo['h_opentime']));
            $res['hotel']['remodeltime'] = date("Y-m-d",strtotime($hinfo['h_remodeltime']));


            //判断是否收藏
            if($uid){
                $has = $clc->where(['uid'=>$uid,'hid'=>$hid])->find();
                if($has){
                    $res['hotel']['collect'] = 1;
                }else{
                    $res['hotel']['collect'] = 0;
                }
            }else{
                $res['hotel']['collect'] = 0;
            }

        }
        $res['room'] = [];
        $pointer = [
            "1"=>'一般',
            "2"=>'普通',
            "3"=>'很好',
            "4"=>'推荐',
            "5"=>'超棒',
        ];

        //获取免费取消设置
        $freemin = 0;
        $res3 = model('Config')->where("name='ordercofig'")->field("value")->find();
        if($res3){
            $restmp = $res3->toarray()["value"];
            $ordercofig = json_decode($restmp,true);
            $freemin = $ordercofig['免费取消时间'];
        }

        //房源信息 具体
        $rinfo = $rdb->where(['id'=>$rid,'h_status'=>'normal','h_statusText'=>'normal','auditing'=>'1'])
            ->field("id,h_title,h_servs,h_service,h_service2,h_read,h_price,h_weekprice,h_img,h_imgs,h_attr,h_point,h_types,h_allprice,tip1,tip2,h_paysytle")->find();



        $closearr = [];
        $closestr = "";

        //房间数据
        if($rinfo){
            //关房逻辑
            // 查询出在日期范围内的不能预定的房间id数组 结合酒店id 缩小范围，所以，不管是单个房间还是同类型推荐的房间都不能存在该数组中 即可。

            $closelist = db("closeroom")
                ->where(["chid"=>$hid])
                ->where("cstime >= '$stime0' && cetime2 <= '$etime24' || cetime2 >='$stime0' && cstime <= '$stime0' || cetime2 >= $stime0 && cstime <= $etime24")
                ->field("crid")
                ->select();

            if($closelist){
                foreach ($closelist as $v){
                    $closearr[] = $v['crid'];
                    $closestr .=  $v['crid'].",";
                }
            }


            //判断房间该时间是否被预定 如果用户改变了时间，刚好被预定，则自动换成同类型其他房源，如果还是为0 则前台变成灰色 不能预定
            $nowroom = true;
            $olist = db("order")
                ->where(["hotelid"=>$hid])
                // ->where(["room_id"=>$rinfo['id']])
                ->where("pay_status='1' || pay_status='2'")
                ->where("stime >= '$stime0' && etime <= '$etime24' || etime >='$stime0' && stime <= '$stime0' || etime >= $stime0 && stime <= $etime24")
                ->field("id,room_id,stime,etime,pay_status")
                ->select();

            if($olist){
                foreach ($olist as $v){
                    $closearr[] = $v['room_id'];
                    $closestr .=  $v['room_id'].",";
                }
            }

            //判断当前房间是否被关闭
            if($closearr){
                if(in_array($rinfo['id'],$closearr)){
                    $nowroom = false;//不能预定 被关闭
                }
            }

            if($closestr != ""){
                $closestr = rtrim($closestr,",");
            }



            //计算同类型房间的数量
            $rtitle = $rinfo['h_title'];
            if(!$nowroom){
                $rcount = $rdb
                    ->where(['h_status'=>'normal','h_statusText'=>'normal','auditing'=>'1','h_title'=>$rtitle])
                    // ->where("id != {$rinfo['id']}")
                    ->where("id not in ($closestr)")
                    ->count();

                //如果同类型房源为0 则不能预定 否自动切换同类型其他房源
                if($rcount > 0){
                    //房源信息 具体
                    $rinfo = $rdb->where(['h_title'=>$rtitle,'h_status'=>'normal','h_statusText'=>'normal','auditing'=>'1'])
                        // ->where("id != {$rinfo['id']}")
                        ->where("h_id = $hid")
                        ->where("id not in ($closestr)")
                        ->field("id,h_title,h_servs,h_service,h_service2,h_read,h_price,h_weekprice,h_img,h_imgs,h_attr,h_point,h_types,h_allprice,tip1,tip2,h_paysytle")->find();
                    $rinfo['stock'] = $rcount;
                }else{
                    $rinfo['stock'] = 0;
                }

            }else{
                $rcount = $rdb
                    ->where(['h_status'=>'normal','h_statusText'=>'normal','auditing'=>'1','h_title'=>$rtitle])
                    ->where("h_id = $hid")
                    ->count();
                $rinfo['stock'] = $rcount;
            }


            //房间属性
            $type = $rinfo['h_types'];
            $typelist = $typedb->where(['status'=>'normal'])->where("id in ($type)")->field("ttitle")->select();
            if($typelist){
                $res['room']['typeslist'] = $typelist;
            }else{
                $res['room']['typeslist'] = [];
            }
            $res['room']['tip1'] = $rinfo['tip1'];
            $res['room']['tip2'] = $rinfo['tip2'];
            $res['room']['freemin'] = $freemin;
            //判断是否支持小时卡
            if($rinfo['h_paysytle']){
                $paystlearr = explode(",",$rinfo['h_paysytle']);
                if(in_array('2',$paystlearr)){
                    $res['room']['canhour'] = 1;
                }else{
                    $res['room']['canhour'] = 0;
                }
            }else{
                $res['room']['canhour'] = 0;
            }


            //服务
            $servs = $rinfo['h_servs'];
            $servsarr = explode(",",$servs);
            $fw = $catedb->where(['status'=>'normal','type'=>'1'])->field("id,name")->select();
            if($fw){
                foreach ($fw as &$v){
                    if(in_array($v['id'],$servsarr)){
                        $v['flag'] = 1;
                    }else{
                        $v['flag'] = 0;
                    }
                }
            }
            //基础
            $jcs = $rinfo['h_service'];
            $jcsarr = explode(",",$jcs);
            $jc = $catedb->where(['status'=>'normal','type'=>'2'])->field("id,name")->select();
            if($jc){
                foreach ($jc as &$v){
                    if(in_array($v['id'],$jcsarr)){
                        $v['flag'] = 1;
                    }else{
                        $v['flag'] = 0;
                    }
                }
            }
            //卫浴
            $wys = $rinfo['h_service2'];
            $wysarr = explode(",",$wys);
            $wy = $catedb->where(['status'=>'normal','type'=>'3'])->field("id,name")->select();
            if($wy){
                foreach ($wy as &$v){
                    if(in_array($v['id'],$wysarr)){
                        $v['flag'] = 1;
                    }else{
                        $v['flag'] = 0;
                    }
                }
            }
            //入住须知
            $rzxz = $rinfo['h_read'];
            $rzxzarr = explode(",",$rzxz);
            $read = $catedb->where(['status'=>'normal','type'=>'4'])->field("id,name")->select();
            if($read){
                foreach ($read as &$v){
                    if(in_array($v['id'],$rzxzarr)){
                        $v['flag'] = 1;
                    }else{
                        $v['flag'] = 0;
                    }
                }
            }

            $res['room']['id'] = $rinfo['id'];
            $res['room']['title'] = $rinfo['h_title'];

            //处理实时价格
            //判断是否有日历价格
            $dateStr = date('Y-m-d 00:00:00', time());
            $timestamp0 = strtotime($dateStr);
            $where["starttime"] = $timestamp0;
            $where["f_id"] = $rinfo["id"];
            $rdata = db("calendar")->where($where)->find();

            if($rdata){
                $res['room']['price'] = sprintf("%1\$.2f",$rdata["title"]);
            }else{
                //判断是否取周末价
                if($w == 5 || $w == 6){
                    if($rinfo["h_weekprice"] != 0){
                        $res['room']['price'] = sprintf("%1\$.2f",$rinfo["h_weekprice"]);
                    }else{
                        $res['room']['price'] = sprintf("%1\$.2f",$rinfo["h_price"]);
                    }
                }else{
                    $res['room']['price'] = $rinfo['h_price'];
                }
            }

            if($ftype == "0"){
                $res['room']['price'] = $rinfo['h_allprice'];
                $res['room']['unit'] = "天";
            }else{
                $res['room']['unit'] = "小时";
            }


            $res['room']['stock'] = $rinfo['stock'];
            $res['room']['img'] = $this->mainhost.$rinfo['h_img'];//封面
            //处理图片
            if($rinfo["h_imgs"]){
                $imgs = array();
                $imgarr = explode(",",$rinfo["h_imgs"]);
                $len = count($imgarr);
                if($len > 1){
                    for ($i=0;$i<$len;$i++){
                        $imgs[$i] = $this->mainhost . $imgarr[$i];
                    }
                }else{
                    $imgs[0] = $this->mainhost . $rinfo["h_imgs"];
                }
                $res['room']["imglist"] = $imgs;
            }else{
                $res['room']["imglist"] = [];

            }

            $res['room']['attr'] = $rinfo['h_attr'];//属性 根据 | 分割

            if($rinfo['h_attr']){
                $res['room']['attr'] = explode("|",$rinfo['h_attr']);
            }else{
                $res['room']['attr'] = [];
            }

            $res['room']['point'] =  sprintf("%1\$.1f",$rinfo["h_point"]);//保留一位小数
            $res['room']['pointname'] = $pointer[$rinfo['h_point']];
            $res['room']['fw'] = $fw;//服务
            $res['room']['jc'] = $jc;//基础
            $res['room']['wy'] = $wy;//卫浴
            $res['room']['read'] = $read;//入住须知
            //查看多少条评论
            $count = $cdb->where(['roomid'=>$rinfo['id'],'userdel'=>0])->count();
            $res['room']['pointcount'] = $count;
            /*                $res['room']['pointitem']['fw'] = 0;//服务态度好
                            $res['room']['pointitem']['bs'] = 0;//老板不错
                            $res['room']['pointitem']['bz'] = 0;//被子干净
                            $res['room']['pointitem']['me'] = 0;//附近有地铁站
                            $res['room']['pointitem']['air'] = 0;//空调好用
                            $res['room']['pointitem']['po'] = 0;//位置不错*/


            if($count > 0){
                //取出最新的评论
                $comlist = $cdb->where(['roomid'=>$rinfo['id'],'userdel'=>0])->order("id desc")->field("uid,ctime,weisheng,memo,imgid,huanjing,fuwu,sheshi,bossnice,position,images")->find();
                if($comlist){
                    $ctext = "";
                    if($comlist['weisheng'] == "1"){
                        $ctext .= "#被子干净";
                    }
                    if($comlist['huanjing'] == "1"){
                        $ctext .= "#空调好用";
                    }
                    if($comlist['fuwu'] == "1"){
                        $ctext .= "#服务态度好";
                    }
                    if($comlist['sheshi'] == "1"){
                        $ctext .= "#附近有地铁站";
                    }
                    if($comlist['bossnice'] == "1"){
                        $ctext .= "#老板不错";
                    }
                    if($comlist['position'] == "1"){
                        $ctext .= "#位置不错";
                    }


                    $res['room']['pointdata']["pdata"]['item'] = $ctext;
                    $res['room']['pointdata']["pdata"]['content'] = $comlist['memo'];
                    $comuserinfo = db("user")->where(["id"=>$comlist['uid']])->find();

                    $res['room']['pointdata']['avatarUrl'] = $comuserinfo['avatarUrl'];
                    $res['room']['pointdata']['time'] = date("Y-m-d H:i:s",$comlist['ctime']);
                    $res['room']['pointdata']['nickName'] =  $comuserinfo['nickName'];
                    $res['room']['pointdata']['content'] = $comlist['memo'];
                    //评论图片
                    if($comlist['images']){
                        //处理图片
                        $imgs = array();
                        $imgarr = explode(",",$comlist["images"]);
                        $len = count($imgarr);
                        if($len > 1){
                            for ($i=0;$i<$len;$i++){
                                $imgs[$i] = $this->mainhost . $imgarr[$i];
                            }
                        }else{
                            $imgs[0] = $this->mainhost . $comlist["images"];
                        }
                        $res['room']['pointdata']['imglist'] = $imgs;
                    }else{

                        $res['room']['pointdata']['imglist'] = [];
                    }


                }else{
                    $res['room']['pointdata'] = [];
                }
                //房客评价打分项
                //服务态度好 老板不错 被子干净 附近有地铁站 空调好用 位置不错

                /*   $res['room']['pointitem']['fw'] = $cdb ->where(["roomid"=>$rinfo['id']])->avg("fuwu");
                   $res['room']['pointitem']['bs'] = $cdb ->where(["roomid"=>$rinfo['id']])->avg("bossnice");;//老板不错
                   $res['room']['pointitem']['bz'] = $cdb ->where(["roomid"=>$rinfo['id']])->avg("weisheng");;//被子干净
                   $res['room']['pointitem']['me'] = $cdb ->where(["roomid"=>$rinfo['id']])->avg("sheshi");;//附近有地铁站
                   $res['room']['pointitem']['air'] = $cdb ->where(["roomid"=>$rinfo['id']])->avg("huanjing");;//空调好用
                   $res['room']['pointitem']['po'] = $cdb ->where(["roomid"=>$rinfo['id']])->avg("position");;//位置不错*/



            }else{
                $res['room']['pointdata'] = [];
            }

        }else{
            $this->error("房源信息有误");
        }


        //其他房源 逻辑：以同类型房源处理，名字相同这代表是同类型 根据名字分组
        //sql 逻辑先分组 然后在统计个人 再取出每组内价格最小的一个房源
        $onetitle = $rinfo['h_title'];
        if($closestr){
            $qtlist = $rdb
                ->where("h_title != '$onetitle'")
                ->where("id not in ($closestr)")
                ->where(['h_id'=>$hid,'h_status'=>'normal','h_statusText'=>'normal','auditing'=>'1'])
                ->field("h_title")
                ->group("h_title")->select();
        }else{
            $qtlist = $rdb
                ->where("h_title != '$onetitle'")
                ->where(['h_id'=>$hid,'h_status'=>'normal','h_statusText'=>'normal','auditing'=>'1'])
                ->field("h_title")
                ->group("h_title")->select();
        }




        //同类型房源 也要判断是否在时间内可以预定
        $qtinfo = [];
        if($qtlist){

            //判断是否有日历价格
            $dateStr2 = date('Y-m-d 00:00:00', time());
            $timestamp1 = strtotime($dateStr2);
            $where2["starttime"] = $timestamp1;
            $templist = [];

            foreach ($qtlist as $k3=>&$v3){
                //获取同类型房源  //这里似乎可以不用再判断 因为 closestr 就是根据条件下筛选出的不能使用的房间id 所以已经排除了，下面就不用再判断，但暂时不做修改，等后续优化时在考虑。
                $tlxrooms =$rdb->where(['h_id'=>$hid,'h_status'=>'normal','h_statusText'=>'normal','auditing'=>'1','h_title'=>$v3['h_title']])->field("id,h_title")->select();
                $or_roomids = "";
                if($tlxrooms){
                    foreach ($tlxrooms as $k=>$txlv){
                        $olist = db("order")
                            ->where(["room_id"=>$txlv['id']])
                            ->where("pay_status='1' || pay_status='2'")
                            ->where("stime >= '$stime0' && etime <= '$etime24' || etime >='$stime0' && stime <= '$stime0' || etime >= $stime0 && stime <= $etime24")
                            ->field("id,room_id,stime,etime,pay_status")
                            ->select();

                        if($olist){
                            foreach ($olist as $ov){
                                $or_roomids .= $ov['room_id'].",";
                                unset($tlxrooms[$k]); //不能预定 切换为其他同类型房源
                            }

                        }
                    }
                }
                $or_roomids = rtrim($or_roomids,",");

                if($or_roomids){
                    $qtinfo = $rdb
                        ->where(['h_id'=>$hid,'h_status'=>'normal','h_statusText'=>'normal','auditing'=>'1','h_title'=>$v3['h_title']])
                        ->where("id not in ($or_roomids)")
                        ->field("id,h_id as hid,h_title as title,h_allprice,h_price as price,h_weekprice,h_img as img,h_stock as stock,h_attr as attr,tip1,tip2,h_paysytle as style")
                        ->order("h_price asc")->find();
                }else{
                    $qtinfo = $rdb
                        ->where(['h_id'=>$hid,'h_status'=>'normal','h_statusText'=>'normal','auditing'=>'1','h_title'=>$v3['h_title']])
                        ->field("id,h_id as hid,h_title as title,h_allprice,h_price as price,h_weekprice,h_img as img,h_stock as stock,h_attr as attr,tip1,tip2,h_paysytle as style")
                        ->order("h_price asc")->find();

                }


                $style = $qtinfo['style'];
                $h_weekprice = $qtinfo['h_weekprice'];
                $price = $qtinfo['price'];
                $h_allprice = $qtinfo['h_allprice'];
                //动态价格
                $where2["f_id"] = $qtinfo["id"];

                $qtinfo['img'] =  $this->mainhost . $qtinfo["img"];
                //判断是否支持小时卡
                if($style){
                    $paystlearr = explode(",",$style);
                    if(in_array('2',$paystlearr)){
                        $qtinfo['canhour'] = 1;
                    }else{
                        $qtinfo['canhour'] = 0;
                    }
                }else{
                    $qtinfo['canhour'] = 0;
                }


                $rdata2 = db("calendar")->where($where2)->find();


                if($rdata2){
                    $qtinfo['price'] = sprintf("%1\$.2f",$rdata2["title"]);
                }else{

                    //判断是否取周末价
                    if($w == 5 || $w == 6){
                        if($h_weekprice != 0){
                            $qtinfo['price'] = sprintf("%1\$.2f",$h_weekprice);
                        }else{
                            $qtinfo['price'] = sprintf("%1\$.2f",$price);
                        }
                    }else{
                        $qtinfo['price'] = $price;
                    }
                }

                if($ftype == "0"){
                    $qtinfo['price'] = $h_allprice;
                    $qtinfo['unit'] = "天";
                }else{
                    $qtinfo['unit'] = "小时";
                }


                $qtinfo['freemin'] = $freemin;
                $qtcount = count($tlxrooms);
                $qtinfo['stock'] = $qtcount;

                if(array_key_exists("id",$qtinfo)){
                    $sort[] = $qtinfo['price'];
                    $templist[] =$qtinfo;
                }


            }
            if($templist){
                //价格排序
                array_multisort($sort,SORT_ASC,$templist);
            }


            $res['qtlist'] = $templist;
        }else{
            $res['qtlist'] = [];
        }

        if($res){
            $this->success("success",$res);
        }else{
            $this->error("数据错误");
        }



    }


    //酒店房间有库存概念
    public function getDetailold(){
        $hdb = db("hotels");
        $rdb = db("house");
        $clc = db("collect");
        $cdb = db("comments");
        $catedb = db("category");
        $typedb = db("type");

        $hid = $this->request->request("hid");
        $rid = $this->request->request("rid");

        $uid = $this->request->request("uid");
        $ftype = $this->request->request("type",1); //0全日房 1 小时房

        if(empty($hid)){
            $this->error("hid不能为空");
        }
        if(empty($rid)){
            $this->error("rid不能为空");
        }
        if(empty($uid)){
            $this->error("uid不能为空");
        }



        $res = [];
        $w=date('w');

        //酒店入口
        if($hid){
            $hinfo = $hdb->where(['hid'=>$hid])->field("hid,hoteltitle,h_tel,h_address,h_content,h_imgs,lng,lat,h_guestroom,h_opentime,h_remodeltime")->find();
            $res['hotel']['hid'] = $hinfo['hid'];
            $res['hotel']['title'] = $hinfo['hoteltitle'];
            $res['hotel']['tel'] = $hinfo['h_tel'];
            $res['hotel']['address'] = $hinfo['h_address'];
            $res['hotel']['content'] = $hinfo['h_content'];
            $res['hotel']['lng'] = $hinfo['lng'];
            $res['hotel']['lat'] = $hinfo['lat'];
            $res['hotel']['guestroom'] = $hinfo['h_guestroom'];
            $res['hotel']['opentime'] = $hinfo['h_opentime'];
            $res['hotel']['remodeltime'] = $hinfo['h_remodeltime'];


            //判断是否收藏
            if($uid){
                $has = $clc->where(['uid'=>$uid,'hid'=>$hid])->find();
                if($has){
                    $res['hotel']['collect'] = 1;
                }else{
                    $res['hotel']['collect'] = 0;
                }
            }else{
                $res['hotel']['collect'] = 0;
            }

        }
        $res['room'] = [];
        $pointer = [
            "1"=>'一般',
            "2"=>'普通',
            "3"=>'很好',
            "4"=>'推荐',
            "5"=>'超棒',
        ];

        if($rid){

            //房源信息 具体
            $rinfo = $rdb->where(['id'=>$rid,'h_status'=>'normal'])
                ->field("id,h_title,h_servs,h_service,h_service2,h_read,h_price,h_weekprice,h_img,h_imgs,h_stock,h_attr,h_point,h_types,h_allprice")->find();

        }else {

            //房源信息 推荐
            $rinfo = $rdb->where("h_stock > 1")->where(['h_id' => $hid, 'h_status' => 'normal'])->order("h_price asc")
                ->field("id,h_title,h_servs,h_service,h_service2,h_read,h_price,h_allprice,h_weekprice,h_img,h_imgs,h_stock,h_attr,h_point,h_types")->find();
            $rid = $rinfo['id'];
        }


        //房间数据
        if($rinfo){
            //房间属性
            $type = $rinfo['h_types'];
            $typelist = $typedb->where(['status'=>'normal'])->where("id in ($type)")->field("ttitle")->select();
            if($typelist){
                $res['room']['typeslist'] = $typelist;
            }else{
                $res['room']['typeslist'] = [];
            }

            //服务
            $servs = $rinfo['h_servs'];
            $servsarr = explode(",",$servs);
            $fw = $catedb->where(['status'=>'normal','type'=>'1'])->field("id,name")->select();
            if($fw){
                foreach ($fw as &$v){
                    if(in_array($v['id'],$servsarr)){
                        $v['flag'] = 1;
                    }else{
                        $v['flag'] = 0;
                    }
                }
            }
            //基础
            $jcs = $rinfo['h_service'];
            $jcsarr = explode(",",$jcs);
            $jc = $catedb->where(['status'=>'normal','type'=>'2'])->field("id,name")->select();
            if($jc){
                foreach ($jc as &$v){
                    if(in_array($v['id'],$jcsarr)){
                        $v['flag'] = 1;
                    }else{
                        $v['flag'] = 0;
                    }
                }
            }
            //卫浴
            $wys = $rinfo['h_service2'];
            $wysarr = explode(",",$wys);
            $wy = $catedb->where(['status'=>'normal','type'=>'3'])->field("id,name")->select();
            if($wy){
                foreach ($wy as &$v){
                    if(in_array($v['id'],$wysarr)){
                        $v['flag'] = 1;
                    }else{
                        $v['flag'] = 0;
                    }
                }
            }
            //入住须知
            $rzxz = $rinfo['h_read'];
            $rzxzarr = explode(",",$rzxz);
            $read = $catedb->where(['status'=>'normal','type'=>'4'])->field("id,name")->select();
            if($read){
                foreach ($read as &$v){
                    if(in_array($v['id'],$rzxzarr)){
                        $v['flag'] = 1;
                    }else{
                        $v['flag'] = 0;
                    }
                }
            }

            $res['room']['id'] = $rinfo['id'];
            $res['room']['title'] = $rinfo['h_title'];

            //处理实时价格
            //判断是否有日历价格
            $dateStr = date('Y-m-d 00:00:00', time());
            $timestamp0 = strtotime($dateStr);
            $where["starttime"] = $timestamp0;
            $where["f_id"] = $rinfo["id"];
            $rdata = db("calendar")->where($where)->find();

            if($rdata){
                $res['room']['price'] = sprintf("%1\$.2f",$rdata["title"]);
            }else{
                //判断是否取周末价
                if($w == 5 || $w == 6){
                    if($rinfo["h_weekprice"] != 0){
                        $res['room']['price'] = sprintf("%1\$.2f",$rinfo["h_weekprice"]);
                    }else{
                        $res['room']['price'] = $rinfo['h_price'];
                    }
                }else{
                    $res['room']['price'] = $rinfo['h_price'];
                }
            }

            if($ftype == "0"){
                $res['room']['price'] = $rinfo['h_allprice'];
                $res['room']['unit'] = "天";
            }else{
                $res['room']['unit'] = "小时";
            }


            $res['room']['stock'] = $rinfo['h_stock'];
            $res['room']['img'] = $this->mainhost.$rinfo['h_img'];//封面
            //处理图片
            if($rinfo["h_imgs"]){
                $imgs = array();
                $imgarr = explode(",",$rinfo["h_imgs"]);
                $len = count($imgarr);
                if($len > 1){
                    for ($i=0;$i<$len;$i++){
                        $imgs[$i] = $this->mainhost . $imgarr[$i];
                    }
                }else{
                    $imgs[0] = $this->mainhost . $rinfo["h_imgs"];
                }
                $res['room']["imglist"] = $imgs;
            }else{
                $res['room']["imglist"] = [];

            }

            $res['room']['attr'] = $rinfo['h_attr'];//属性 根据 | 分割

            if($rinfo['h_attr']){
                $res['room']['attr'] = explode("|",$rinfo['h_attr']);
            }else{
                $res['room']['attr'] = [];
            }

            $res['room']['point'] =  sprintf("%1\$.1f",$rinfo["h_point"]);//保留一位小数
            $res['room']['pointname'] = $pointer[$rinfo['h_point']];
            $res['room']['fw'] = $fw;//服务
            $res['room']['jc'] = $jc;//基础
            $res['room']['wy'] = $wy;//卫浴
            $res['room']['read'] = $read;//入住须知
            //查看多少条评论
            $count = $cdb->where(['roomid'=>$rinfo['id'],'userdel'=>0])->count();
            $res['room']['pointcount'] = $count;
            /*                $res['room']['pointitem']['fw'] = 0;//服务态度好
                            $res['room']['pointitem']['bs'] = 0;//老板不错
                            $res['room']['pointitem']['bz'] = 0;//被子干净
                            $res['room']['pointitem']['me'] = 0;//附近有地铁站
                            $res['room']['pointitem']['air'] = 0;//空调好用
                            $res['room']['pointitem']['po'] = 0;//位置不错*/
            if($count > 0){
                //取出最新的评论
                $comlist = $cdb->where(['roomid'=>$rinfo['id'],'userdel'=>0])->order("id desc")->field("uid,ctime,weisheng,memo,imgid,huanjing,fuwu,sheshi,bossnice,position,images")->find();
                if($comlist){
                    $ctext = "";
                    if($comlist['weisheng'] == "1"){
                        $ctext .= "#被子干净";
                    }
                    if($comlist['huanjing'] == "1"){
                        $ctext .= "#空调好用";
                    }
                    if($comlist['fuwu'] == "1"){
                        $ctext .= "#服务态度好";
                    }
                    if($comlist['sheshi'] == "1"){
                        $ctext .= "#附近有地铁站";
                    }
                    if($comlist['bossnice'] == "1"){
                        $ctext .= "#老板不错";
                    }
                    if($comlist['position'] == "1"){
                        $ctext .= "#位置不错";
                    }


                    $res['room']['pointdata']["pdata"]['item'] = $ctext;
                    $res['room']['pointdata']["pdata"]['content'] = $comlist['memo'];
                    $comuserinfo = db("user")->where(["id"=>$comlist['uid']])->find();

                    $res['room']['pointdata']['avatarUrl'] = $comuserinfo['avatarUrl'];
                    $res['room']['pointdata']['time'] = date("Y-m-d H:i:s",$comlist['ctime']);
                    $res['room']['pointdata']['nickName'] =  $comuserinfo['nickName'];
                    $res['room']['pointdata']['content'] = $comlist['memo'];
                    //评论图片
                    if($comlist['images']){
                        //处理图片
                        $imgs = array();
                        $imgarr = explode(",",$comlist["images"]);
                        $len = count($imgarr);
                        if($len > 1){
                            for ($i=0;$i<$len;$i++){
                                $imgs[$i] = $this->mainhost . $imgarr[$i];
                            }
                        }else{
                            $imgs[0] = $this->mainhost . $comlist["images"];
                        }
                        $res['room']['pointdata']['imglist'] = $imgs;
                    }else{

                        $res['room']['pointdata']['imglist'] = [];
                    }


                    /*if($comlist['imgid']){
                        $cimgdata = db("comments_img")->where(['id'=>$comlist['imgid']])->find();
                        if($cimgdata['image']){
                            //处理图片
                            $imgs = array();
                            $imgarr = explode(",",$cimgdata["image"]);
                            $len = count($imgarr);
                            if($len > 1){
                                for ($i=0;$i<$len;$i++){
                                    $imgs[$i] = $this->mainhost . $imgarr[$i];
                                }
                            }else{
                                $imgs[0] = $this->mainhost . $cimgdata["image"];
                            }
                        }

                        $res['room']['pointdata']['imglist'] = $imgs;
                    }else{
                        $res['room']['pointdata']['imglist'] = [];
                    }*/

                }else{
                    $res['room']['pointdata'] = [];
                }
                //房客评价打分项
                //服务态度好 老板不错 被子干净 附近有地铁站 空调好用 位置不错

                /*   $res['room']['pointitem']['fw'] = $cdb ->where(["roomid"=>$rinfo['id']])->avg("fuwu");
                   $res['room']['pointitem']['bs'] = $cdb ->where(["roomid"=>$rinfo['id']])->avg("bossnice");;//老板不错
                   $res['room']['pointitem']['bz'] = $cdb ->where(["roomid"=>$rinfo['id']])->avg("weisheng");;//被子干净
                   $res['room']['pointitem']['me'] = $cdb ->where(["roomid"=>$rinfo['id']])->avg("sheshi");;//附近有地铁站
                   $res['room']['pointitem']['air'] = $cdb ->where(["roomid"=>$rinfo['id']])->avg("huanjing");;//空调好用
                   $res['room']['pointitem']['po'] = $cdb ->where(["roomid"=>$rinfo['id']])->avg("position");;//位置不错*/



            }else{
                $res['room']['pointdata'] = [];
            }

        }


        //其他房源 逻辑：正常房源 库存充足的
        $qtlist = $rdb->where("id != $rid ")->where("h_stock > 1")->where(['h_id'=>$hid,'h_status'=>'normal'])->order("h_price asc")
            ->field("id,h_id as hid,h_title as title,h_allprice,h_price as price,h_weekprice,h_img as img,h_stock as stock,h_attr as attr")->select();

        //判断是否有日历价格
        $dateStr2 = date('Y-m-d 00:00:00', time());
        $timestamp1 = strtotime($dateStr2);
        $where2["starttime"] = $timestamp1;

        if($qtlist){
            foreach ($qtlist as &$vv){

                $vv['img']  = $this->mainhost . $vv["img"];

                if($vv['attr']){
                    $vv['attr'] = explode("|",$vv['attr']);
                }else{
                    $vv['attr'] = [];
                }
                //动态价格
                $where2["f_id"] = $vv["id"];
                $rdata2 = db("calendar")->where($where2)->find();
                if($rdata2){
                    $vv['price'] = sprintf("%1\$.2f",$rdata2["title"]);
                }else{
                    //判断是否取周末价
                    if($w == 5 || $w == 6){
                        if($vv["h_weekprice"] != 0){
                            $vv['price'] = sprintf("%1\$.2f",$vv["h_weekprice"]);
                        }else{
                            $vv['price'] = $vv['price'];
                        }
                    }else{
                        $vv['price'] = $vv['price'];
                    }
                }

                if($ftype == "0"){
                    $vv['price'] = $vv['h_allprice'];
                    $vv['unit'] = "天";
                }else{
                    $vv['unit'] = "小时";
                }

                unset($vv['h_weekprice']);


            }
        }

        $res['qtlist'] = $qtlist;

        if($res){
            $this->success("success",$res);
        }else{
            $this->error("数据错误");
        }



    }


    //选单个房源信息
    public function getOnedetail(){
        $rid = $this->request->request("rid");
        $ftype = $this->request->request("type");
        if(empty($rid)){
            $this->error("房间参数错误");
        }
        $rdb = db("house");
        //房源信息 具体
        $rinfo = $rdb->where(['id'=>$rid])
            ->field("id,h_title as title,h_price as price,h_allprice,h_weekprice,h_imgs as imgs,h_mi as mi,h_people as people,h_wifi as wifi,h_win as win,h_bed as bed,h_smoke as smoke,h_food as food")->find();


        if($rinfo){
            //处理图片
            if($rinfo["imgs"]){
                $imgs = array();
                $imgarr = explode(",",$rinfo["imgs"]);
                $len = count($imgarr);
                if($len > 1){
                    for ($i=0;$i<$len;$i++){
                        $imgs[$i] = $this->mainhost . $imgarr[$i];
                    }
                }else{
                    $imgs[0] = $this->mainhost . $rinfo["imgs"];
                }
                $rinfo["imglist"] = $imgs;
            }else{
                $rinfo["imglist"] = [];

            }
            unset($rinfo['imgs']);
            //处理价格
            $w=date('w');
            //判断是否有日历价格
            $dateStr = date('Y-m-d 00:00:00', time());
            $timestamp0 = strtotime($dateStr);
            $where["starttime"] = $timestamp0;
            $where["f_id"] = $rinfo["id"];
            $rdata = db("calendar")->where($where)->find();
            if($rdata){
                $rinfo['price'] = sprintf("%1\$.2f",$rdata["title"]);
            }else{
                //判断是否取周末价
                if($w == 5 || $w == 6){
                    if($rinfo["h_weekprice"] != 0){
                        $rinfo['price'] = sprintf("%1\$.2f",$rinfo["h_weekprice"]);
                    }else{
                        $rinfo['price'] = $rinfo['price'];
                    }
                }else{
                    $rinfo['price'] = $rinfo['price'];
                }
            }

            if($ftype == "0"){
                $rinfo['price'] = $rinfo['h_allprice'];
                $rinfo['unit'] = "天";
            }else{
                $rinfo['unit'] = "小时";
            }

            unset($rinfo['h_allprice']);
            unset($rinfo['h_weekprice']);


            $this->success("success",$rinfo);
        }else{
            $this->error("数据错误");
        }


    }

    //获取标签
    public function getLabel(){
        $list = db("label")->where(['status'=>'normal'])->field("id,ltitle")->order("lcount desc")->select();
        if($list){
            $app=array("id"=>"all","ltitle"=>"全部");
            array_unshift($list,$app);
            $this->success("success",$list);
        }else{
            $this->error("数据有误");
        }
    }

    //宾馆列表
    public function getHlist(){
        $hdb = db("hotels");
        $lbs = db("label");
        $tps = db("type");
        $htps = db("htype");
        $rdb = db("house");
        $w=date('w');

        //城市经纬度
        $lng1 = $this->request->request("lng");
        $lat1 = $this->request->request("lat");


        //用户经纬度
        //$lng1 = $this->request->request("userlng");
        //$lat1 = $this->request->request("userlat");


        $citycode = $this->request->request("citycode");//城市编码
        $lid = $this->request->request("lid");//标签id
        $title = $this->request->request("title");//关键词
        $ftype = $this->request->request("type",1);//类型 1小时房 0全日房 默认1

        //开始结束时间 用来 筛选单价  需要判断用户选择的时间内房源是否被预定，如果预定 则不返回该房间数据
        $stime = $this->request->request("stime");//开始时间
        if($stime){
            $prestime = strtotime($stime);
            $stime0 = strtotime(date('Y-m-d',strtotime($stime)));//用户选择的开始时间的0点
            $stime24 = strtotime(date("Y-m-d 23:59:59",strtotime($stime)));
        }
        $etime = $this->request->request("etime");//结束时间
        if($etime){
            $preetime = strtotime($etime);
            $etime0 = strtotime(date('Y-m-d',strtotime($etime))) ;//用户选择的结束时间的0点
            $etime24 = strtotime(date("Y-m-d 23:59:59",strtotime($etime)));
        }

        //新增判断 小时房必须 2小时起步
        if($ftype == '1'){
            if($preetime - $prestime < 7200){
                $this->error("时租房预定两小时起步");
            }
        }


        //排序
        $order = $this->request->request("order","hid");//结束时间
        $adsc = $this->request->request("adsc","asc");//结束时间
        $order2 = "";
        if($order == "park"){
            $order = "h_parking";
        }elseif ($order == "distance"){
            $order = "hid";
            $order2 = "distance";//距离排序 是数组排序，不用改动sql
        }elseif ($order == "point"){
            $order = "h_point";
        }else{
            $order = "hid";
        }


        $page = $this->request->request("page",1);
        $limit = $this->request->request("limit",10000);//无限大

        if(empty($citycode)){
            $this->error('城市参数错误');
        }
        if(empty($lid)){
            $this->error('标签参数错误');
        }
        if(empty($lng1) || empty($lat1)){
            $this->error('经纬度参数错误');
        }
        //关键词搜索 扩展 根据属性搜索
        $where = "";
        if($title){
            $where = "`hoteltitle` LIKE '%$title%'" ;

            if($title == "小时卡"){
                $where .= " || `h_parking` = '1'" ;
            }

            $typeinfo = $htps->where("`ttitle` LIKE '%$title%'")->field("id")->select();

            if($typeinfo){
                foreach ($typeinfo as $vt){
                    $tid = $vt['id'];
                    $where .= " || FIND_IN_SET($tid,`h_htypes`) ";
                }
            }
        }


        //距离排序单独处理
        if($order2 == "distance"){
            if($lid == "all"){
                $list = $hdb
                    ->where(['h_status'=>'normal','h_areadid'=>$citycode])
                    ->where($where)
                    ->field("hid,hoteltitle as title,h_img as img,lng,lat,h_lebals as labels,h_htypes as htypes,h_types as types,h_point as point,h_parking")
                    ->select();
            }else{
                $list = $hdb
                    ->where(['h_status'=>'normal','h_areadid'=>$citycode])
                    ->where($where)
                    ->where("FIND_IN_SET($lid,`h_lebals`)")
                    ->field("hid,hoteltitle as title,h_img as img,lng,lat,h_lebals as labels,h_htypes as htypes,h_types as types,h_point as point,h_parking")
                    ->select();
            }

        }else{

            if($lid == "all"){
                $list = $hdb
                    ->where(['h_status'=>'normal','h_areadid'=>$citycode])
                    ->where($where)
                    ->field("hid,hoteltitle as title,h_img as img,lng,lat,h_lebals as labels,h_htypes as htypes,h_types as types,h_point as point,h_parking")
                    ->order($order,$adsc)
                    ->select();
            }else{
                $list = $hdb
                    ->where(['h_status'=>'normal','h_areadid'=>$citycode])
                    ->where($where)
                    ->where("FIND_IN_SET($lid,`h_lebals`)")
                    ->field("hid,hoteltitle as title,h_img as img,lng,lat,h_lebals as labels,h_htypes as htypes,h_types as types,h_point as point,h_parking")
                    ->order($order,$adsc)
                    ->select();
            }
        }


        //平分等级 目前只考虑整数 评论分 1一般 2 普通 3 很好 4 推荐 5 超棒
        $pointer = [
            "1"=>'一般',
            "2"=>'普通',
            "3"=>'很好',
            "4"=>'推荐',
            "5"=>'超棒',
        ];

        ////新增排除关房房间

        $closearr[] =[];
        $closestr = "";
        //处理逻辑 筛选出酒店下不能预定的房间id 排除这些 随机选择一个 即可
        //关闭的房间数据
        $closelist = db("closeroom")
            ->where("cstime >= '$stime0' && cetime2 <= '$etime24' || cetime2 >='$stime0' && cstime <= '$stime0' || cetime2 >= $stime0 && cstime <= $etime24")
            ->field("crid")
            ->select();

        if($closelist){
            foreach ($closelist as $v2){
                $closearr[] = $v2['crid'];
                $closestr .=  $v2['crid'].",";
            }
        }


        if($list){
            $templist = [];
            foreach ($list as $k=>&$v){

                //处理酒店下符合条件房间：1.房间必须审核通过，且是空闲状态 如果没有符合条件房源，则该酒店则不显示 如果酒店支持小时卡 优先推荐小时卡房源
                //获取时间内占用的房间数据
                $olist = db("order")
                    ->where(['hotelid'=>$v['hid']])
                    ->where("pay_status = '1' || pay_status = '2'")
                    ->where("stime >= '$stime0' && etime <= '$etime24' || etime >='$stime0' && stime <= '$stime0' || etime >= $stime0 && stime <= $etime24")
                    ->field("id,room_id,hotelid")
                    ->select();

                if($olist){
                    foreach ($olist as $vv){
                        $closearr[] = $vv['room_id'];
                        $closestr .=  $vv['room_id'].",";
                    }
                }

                if($closestr){
                    $closestr = rtrim($closestr,",");
                }

                if($closestr){

                    if($v['h_parking'] == 1){
                        $info = $rdb
                            ->where(['h_id'=>$v['hid'],'h_status'=>'normal','h_statusText'=>'normal','auditing'=>'1'])
                            ->where("id not in ($closestr)")
                            ->where("FIND_IN_SET('2',`h_paysytle`)")
                            ->field("fa_house.id,h_id,h_price,h_weekprice,h_allprice,h_paysytle")
                            ->order("h_price asc")
                            ->find();

                    }else{
                        $info = $rdb->where(['h_id'=>$v['hid'],'h_status'=>'normal','h_statusText'=>'normal','auditing'=>'1'])->where("id not in ($closestr)")->field("id,h_id,h_price,h_weekprice,h_allprice,h_paysytle")->order("h_price asc")->find();
                    }
                }else{
                    if($v['h_parking'] == 1){

                        $info = $rdb
                            ->where(['h_id'=>$v['hid'],'h_status'=>'normal','h_statusText'=>'normal','auditing'=>'1'])
                            ->where("FIND_IN_SET('2',`h_paysytle`)")
                            ->field("fa_house.id,h_id,h_price,h_weekprice,h_allprice,h_paysytle")
                            ->order("h_price asc")
                            ->find();

                    }else{
                        $info = $rdb->where(['h_id'=>$v['hid'],'h_status'=>'normal','h_statusText'=>'normal','auditing'=>'1'])->field("id,h_id,h_price,h_weekprice,h_allprice,h_paysytle")->order("h_price asc")->find();
                    }
                }

                if(!$info){
                    continue;
                }

                $types = [];
                $typearr = [];
                $nowpont = $v['point'];
                if($nowpont<1){
                    $nowpont = 1;
                }
                if($nowpont>51){
                    $nowpont = 5;
                }


                $v['pointname'] = $pointer[$nowpont];
                $v['img'] = $this->mainhost.$v['img'];
                //房属性
                $type = $v["types"];
                if($type){
                    $typearr = $tps->where("id in ($type)")->field("ttitle")->select();
                }

                if($typearr){
                    foreach ($typearr as $vv){
                        if($vv['ttitle'] == "小时卡"){
                            continue;
                        }
                        $types[] = $vv["ttitle"] ;
                    }
                }

                //房型
                $labels = [];
                $labelarr = [];
                $label = $v["htypes"];
                if($label){
                    $labelarr = $htps->where("id in ($label)")->field("ttitle")->select();
                }

                if($labelarr){
                    foreach ($labelarr as $vv){
                        $labels[] = $vv["ttitle"] ;
                    }
                }
                $v['types'] = $types;
                $v['htypes'] = $labels;

                //多少分钟前有人预定 ，这里随机一个数字
                $v['min'] = mt_rand(10,40)."分钟前有人预定";


                if($info){
                    $v['rid'] = $info['id'];//房间id
                    //判断是否有日历价格 如果用户选择开始时间 要以 用户选择的时间段为准 考虑是否在活动或者周末价范围

                    if($stime){
                        $stime = strtotime($stime);
                        $dateStr = date('Y-m-d 00:00:00',$stime);
                    }else{
                        $dateStr = date('Y-m-d 00:00:00', time());
                    }
                    $timestamp0 = strtotime($dateStr);
                    $where2["starttime"] = $timestamp0;
                    $where2["f_id"] = $info["id"];
                    $rdata = db("calendar")->where($where2)->find();

                    if($rdata){
                        $v['price'] = sprintf("%1\$.2f",$rdata["title"]);
                    }else{

                        //判断是否取周末价
                        if($w == 5 || $w == 6){
                            if($info["h_weekprice"] != 0){
                                $v['price'] = sprintf("%1\$.2f",$info["h_weekprice"]);
                            }else{
                                $v['price'] = sprintf("%1\$.2f",$info["h_price"]);
                            }
                        }else{
                            $v['price'] = $info['h_price'];
                        }
                    }

                    //判断显示全日价 时租价

                    if($ftype == 1){
                        $v['unit'] = "小时";
                    }else{
                        $v['price'] = $info['h_allprice'];
                        $v['unit'] = "天";
                    }
                }


                //备注文字
                $v['tip'] = "随时可住，2小时起租";

                if(!$v["lng"] || !$v["lat"]){
                    continue;
                }


                //距离
                $v["distance"] = "距离定位位置".getdistancekm($lng1,$lat1,$v["lng"],$v["lat"])."km";

                $v['distance2'] = getdistancekm($lng1,$lat1,$v["lng"],$v["lat"]);

                $templist[$k] = $v;

            }

            //总数据数量
            $count = count($templist);

            //自定义分页
            $offset = ($page-1)*$limit;
            $templist = array_slice($templist,$offset,$limit);


            //如果进行距离排序 修改这里
            if($order2 == "distance" && $adsc == "asc"){
                // array_multisort($sort,SORT_ASC,$templist);
                $templist = arraySequence($templist,'distance2','SORT_ASC');
                $offset = ($page-1)*$limit;
                $templist = array_slice($templist,$offset,$limit);
            }
            if ($order2 == "distance" &&  $adsc == "desc"){
                $templist = arraySequence($templist,'distance2','SORT_DESC');
                $offset = ($page-1)*$limit;
                $templist = array_slice($templist,$offset,$limit);
            }

            $res["rowCount"] = $count;
            $res["pageSize"] = $limit;
            $res["pageIndex"] = $page;
            $res["pageCount"] = ceil($count/$limit);
            $res["rowData"] = $templist;

            $this->success("success",$res);
        }else{
            $this->error("暂无数据");
        }


    }


    //宾馆列表 去掉分页
    public function getHlist20211211(){
        $hdb = db("hotels");
        $lbs = db("label");
        $tps = db("type");
        $htps = db("htype");
        $rdb = db("house");
        $w=date('w');

        $lng1 = $this->request->request("lng");
        $lat1 = $this->request->request("lat");
        $citycode = $this->request->request("citycode");//城市编码
        $lid = $this->request->request("lid");//标签id
        $title = $this->request->request("title");//关键词
        $ftype = $this->request->request("type",1);//类型 1小时房 0全日房 默认1

        //开始结束时间 用来 筛选单价  需要判断用户选择的时间内房源是否被预定，如果预定 则不返回该房间数据
        $stime = $this->request->request("stime");//开始时间
        if($stime){
            $prestime = strtotime($stime);
            $stime0 = strtotime(date('Y-m-d',strtotime($stime)));//用户选择的开始时间的0点
            $stime24 = strtotime(date("Y-m-d 23:59:59",strtotime($stime)));
        }
        $etime = $this->request->request("etime");//结束时间
        if($etime){
            $preetime = strtotime($etime);
            $etime0 = strtotime(date('Y-m-d',strtotime($etime))) ;//用户选择的结束时间的0点
            $etime24 = strtotime(date("Y-m-d 23:59:59",strtotime($etime)));
        }

        //新增判断 小时房必须 2小时起步
        if($ftype == '1'){
            if($preetime - $prestime < 7200){
                $this->error("时租房预定两小时起步");
            }
        }


        //排序
        $order = $this->request->request("order","hid");//结束时间
        $adsc = $this->request->request("adsc","asc");//结束时间
        $order2 = "";
        if($order == "park"){
            $order = "h_parking";
        }elseif ($order == "distance"){
            $order = "hid";
            $order2 = "distance";//距离排序 是数组排序，不用改动sql
        }elseif ($order == "point"){
            $order = "h_point";
        }else{
            $order = "hid";
        }


        $page = $this->request->request("page",1);
        $limit = $this->request->request("limit",10);

        if(empty($citycode)){
            $this->error('城市参数错误');
        }
        if(empty($lid)){
            $this->error('标签参数错误');
        }
        if(empty($lng1) || empty($lat1)){
            $this->error('经纬度参数错误');
        }
        //关键词搜索 扩展 根据属性搜索
        $where = "";
        if($title){
            $where = "`hoteltitle` LIKE '%$title%'" ;

            if($title == "小时卡"){
                $where .= " || `h_parking` = '1'" ;
            }

            $typeinfo = $htps->where("`ttitle` LIKE '%$title%'")->field("id")->select();

            if($typeinfo){
                foreach ($typeinfo as $vt){
                    $tid = $vt['id'];
                    $where .= " || FIND_IN_SET($tid,`h_htypes`) ";
                }
            }
        }


        //距离排序单独处理
        if($order2 == "distance"){
            if($lid == "all"){
                $list = $hdb
                    ->where(['h_status'=>'normal','h_areadid'=>$citycode])
                    ->where($where)
                    ->field("hid,hoteltitle as title,h_img as img,lng,lat,h_lebals as labels,h_htypes as htypes,h_types as types,h_point as point,h_parking")
                    ->select();
            }else{
                $list = $hdb
                    ->where(['h_status'=>'normal','h_areadid'=>$citycode])
                    ->where($where)
                    ->where("FIND_IN_SET($lid,`h_lebals`)")
                    ->field("hid,hoteltitle as title,h_img as img,lng,lat,h_lebals as labels,h_htypes as htypes,h_types as types,h_point as point,h_parking")
                    ->select();
            }

        }else{

            if($lid == "all"){
                $list = $hdb
                    ->where(['h_status'=>'normal','h_areadid'=>$citycode])
                    ->where($where)
                    ->field("hid,hoteltitle as title,h_img as img,lng,lat,h_lebals as labels,h_htypes as htypes,h_types as types,h_point as point,h_parking")
                    ->order($order,$adsc)
                    ->select();
            }else{
                $list = $hdb
                    ->where(['h_status'=>'normal','h_areadid'=>$citycode])
                    ->where($where)
                    ->where("FIND_IN_SET($lid,`h_lebals`)")
                    ->field("hid,hoteltitle as title,h_img as img,lng,lat,h_lebals as labels,h_htypes as htypes,h_types as types,h_point as point,h_parking")
                    ->order($order,$adsc)
                    ->select();
            }
        }


        //平分等级 目前只考虑整数 评论分 1一般 2 普通 3 很好 4 推荐 5 超棒
        $pointer = [
            "1"=>'一般',
            "2"=>'普通',
            "3"=>'很好',
            "4"=>'推荐',
            "5"=>'超棒',
        ];


        if($list){
            $templist = [];
            foreach ($list as $k=>&$v){

                //处理酒店下符合条件房间：1.房间必须审核通过，且是空闲状态 如果没有符合条件房源，则该酒店则不显示 如果酒店支持小时卡 优先推荐小时卡房源
                //获取时间内占用的房间数据
                $olist = db("order")
                    ->where(['hotelid'=>$v['hid']])
                    ->where("pay_status = '1' || pay_status = '2'")
                    ->where("stime >= '$stime0' && etime <= '$etime24' || etime >='$stime0' && stime <= '$stime0' || etime >= $stime0 && stime <= $etime24")
                    ->field("id,room_id,hotelid")
                    ->select();

                $noids = "";
                if($olist){
                    foreach ($olist as $ov){
                        $noids .= $ov['room_id'].",";
                    }
                }

                if($noids){
                    $noids = rtrim($noids,",");
                    if($v['h_parking'] == 1){
                        $info = $rdb
                            ->where(['h_id'=>$v['hid'],'h_status'=>'normal','h_statusText'=>'normal','auditing'=>'1'])
                            ->where("id not in ($noids)")
                            ->where("FIND_IN_SET('2',`h_paysytle`)")
                            ->field("fa_house.id,h_id,h_price,h_weekprice,h_allprice,h_paysytle")
                            ->order("h_price asc")
                            ->find();

                    }else{
                        $info = $rdb->where(['h_id'=>$v['hid'],'h_status'=>'normal','h_statusText'=>'normal','auditing'=>'1'])->where("id not in ($noids)")->field("id,h_id,h_price,h_weekprice,h_allprice,h_paysytle")->order("h_price asc")->find();
                    }
                }else{
                    if($v['h_parking'] == 1){

                        $info = $rdb
                            ->where(['h_id'=>$v['hid'],'h_status'=>'normal','h_statusText'=>'normal','auditing'=>'1'])
                            ->where("FIND_IN_SET('2',`h_paysytle`)")
                            ->field("fa_house.id,h_id,h_price,h_weekprice,h_allprice,h_paysytle")
                            ->order("h_price asc")
                            ->find();

                    }else{
                        $info = $rdb->where(['h_id'=>$v['hid'],'h_status'=>'normal','h_statusText'=>'normal','auditing'=>'1'])->field("id,h_id,h_price,h_weekprice,h_allprice,h_paysytle")->order("h_price asc")->find();
                    }
                }

                if(!$info){
                    continue;
                }

                $types = [];
                $typearr = [];

                $nowpont = $v['point'];
                if($nowpont<1){
                    $nowpont = 1;
                }
                if($nowpont>51){
                    $nowpont = 5;
                }

                $v['pointname'] = $pointer[$nowpont];
                $v['img'] = $this->mainhost.$v['img'];
                //房属性
                $type = $v["types"];
                if($type){
                    $typearr = $tps->where("id in ($type)")->field("ttitle")->select();
                }

                if($typearr){
                    foreach ($typearr as $vv){
                        if($vv['ttitle'] == "小时卡"){
                            continue;
                        }
                        $types[] = $vv["ttitle"] ;
                    }
                }

                //房型
                $labels = [];
                $labelarr = [];
                $label = $v["htypes"];
                if($label){
                    $labelarr = $htps->where("id in ($label)")->field("ttitle")->select();
                }

                if($labelarr){
                    foreach ($labelarr as $vv){
                        $labels[] = $vv["ttitle"] ;
                    }
                }
                $v['types'] = $types;
                $v['htypes'] = $labels;

                //多少分钟前有人预定 ，这里随机一个数字
                $v['min'] = mt_rand(10,40)."分钟前有人预定";

                if($info){
                    $v['rid'] = $info['id'];//房间id
                    //判断是否有日历价格 如果用户选择开始时间 要以 用户选择的时间段为准 考虑是否在活动或者周末价范围

                    if($stime){
                        $stime = strtotime($stime);
                        $dateStr = date('Y-m-d 00:00:00',$stime);
                    }else{
                        $dateStr = date('Y-m-d 00:00:00', time());
                    }
                    $timestamp0 = strtotime($dateStr);
                    $where2["starttime"] = $timestamp0;
                    $where2["f_id"] = $info["id"];
                    $rdata = db("calendar")->where($where2)->find();

                    if($rdata){
                        $v['price'] = sprintf("%1\$.2f",$rdata["title"]);
                    }else{

                        //判断是否取周末价
                        if($w == 5 || $w == 6){
                            if($info["h_weekprice"] != 0){
                                $v['price'] = sprintf("%1\$.2f",$info["h_weekprice"]);
                            }else{
                                $v['price'] = sprintf("%1\$.2f",$info["h_price"]);
                            }
                        }else{
                            $v['price'] = $info['h_price'];
                        }
                    }

                    //判断显示全日价 时租价

                    if($ftype == 1){
                        $v['unit'] = "小时";
                    }else{
                        $v['price'] = $info['h_allprice'];
                        $v['unit'] = "天";
                    }
                }

                //备注文字
                $v['tip'] = "随时可住，2小时起租";

                //距离
                $v["distance"] = "距离定位位置".getdistancekm($lng1,$lat1,$v["lng"],$v["lat"])."km";
                $sort[] = $v["distance"];
                $templist[$k] = $v;

            }


            //总数据数量
            $count = count($templist);

            //自定义分页
            $offset = ($page-1)*$limit;
            $templist = array_slice($templist,$offset,$limit);


            //如果进行距离排序 修改这里
            if($order2 == "distance" && $adsc == "asc"){
                array_multisort($sort,SORT_ASC,$templist);
                $offset = ($page-1)*$limit;
                $templist = array_slice($templist,$offset,$limit);
            }
            if ($order2 == "distance" &&  $adsc == "desc"){
                array_multisort($sort,SORT_DESC,$templist);

                $offset = ($page-1)*$limit;
                $templist = array_slice($templist,$offset,$limit);
            }



            print_r($templist);die;


            $res["rowCount"] = $count;
            $res["pageSize"] = $limit;
            $res["pageIndex"] = $page;
            $res["pageCount"] = ceil($count/$limit);
            $res["rowData"] = $templist;

            $this->success("success",$res);
        }else{
            $this->error("暂无数据");
        }


    }




    //提交订单 暂时为生成订单
    //支付分三种：全日房 不要押金 小时房（如果有结束日期也不要押金） 小时房（未选择结束日期则是全日房费押金）
    //说明：计费规则
    //0.00 - 6.00 当天12点退房
    //6.00 - 24.00 次天12点退房
    //如果是全日房 就考虑常规订房 目前多数城市的酒店是按照国际惯例执行，宾馆的入住时间为14：00，离店时间为正午12：00。按此时段进行入住收取1晚房费。

    //这里留下一个思考：如果用户小时房的费用超过了总房费，则最多扣除总房费，但是理论上 他是可以住到全天的时长，但是这里他选择了结束时间，所以程序就以他选择的时间为准，
    //后续如果有必要，再沟通改变，暂时先以选择时间为准。

    protected function computerOrder($uid,$rid,$timing,$stime,$etime){

        //$timing//全日房或者小时房 0全日房 1小时房（有结束时间） 2小时房（无结束时间）
        //全日房不计算 hour min 等信息 ；小时房（有结束日期）需要开始就记录； 小时房（无结束时间）退房时记录
        //每天按固定小时计算
        $dayhour = 10;
        $config = db('Config')->where("id=37")->field("value")->find();
        if($config && $config['value']){
            $dayhour = $config['value'];
        }

        //入住时间 动态获取
        $stimepre = strtotime($stime);
        $instime = 0;
        $outtime = 0;
        $overmine = 0;//超过配置分钟 则算作一小时
        $jftime = 0;
        $res3 = model('Config')->where("name='ordercofig'")->field("value")->find();
        if($res3){
            $restmp = $res3->toarray()["value"];
            $ordercofig = json_decode($restmp,true);
            $instime = $stimepre + $ordercofig['计费时间'] * 60;
            $jftime =  $ordercofig['计费时间'] * 60;
            $outtime = $ordercofig['允许延迟退房'] * 60;
            $overmine = $ordercofig['超分算时'];
        }

        $instimedate = date('Y-m-d H:i',$instime);

        //返回数据
        $res = [];
        $text = "";
        $explain = "";
        $money = 0;
        $hour = 0;
        $min = 0;
        $now = time();
        //获取预定当天 开始时间 0 点 6点 时间
        $stime0 = strtotime(date("Y-m-d 00:00:00",strtotime($stime)));
        $stime6 = $stime0 + 3600*6;
        $stime12 = $stime0 + 3600*12;
        //判断如果是今天的全日房 入住时间就实时
        $system0 = strtotime(date("Y-m-d",$now));
        if($system0 == $stime0){
            $stime14 = $now + $jftime;
        }else{
            $stime14 = $stime0 + 3600*14;
        }
        $stime36 = $stime0 + 3600*36;
        //判断指定日期是周几
        $w = date("w",$stime0);
        if(empty($uid)){
            $this->error("用户参数错误");
        }
        //获取当前用户信息
        $uinfo = db("user")->where(['id'=>$uid])->field("nickName,phone")->find();

        if(!$uinfo){
            $this->error("房间信息错误");
        }

        $res['user'] = $uinfo;

        if($timing == ""){
            $this->error("订房类型不能为空");
        }
        if(!in_array($timing,[0,1,2])){
            $this->error("订房类型不合法");
        }

        if(empty($stime)){
            $this->error("开始时间不能为空");
        }

        //存在结束时间
        if($etime){

            $etimepre = strtotime($etime);
            if($timing == "1" || $timing == "2"){
                //超过次日12提示小时房不可以超过1天
                if($etimepre > $stime36){
                    $this->error("小时房不能跨度次日12点");
                }
                if($timing == '1'){
                    if(($etimepre - $stimepre) < 7200){
                        $this->error("分时房两小时起租！");
                    }
                }

            }

            $etimepre2 = $etimepre + $outtime;
            $outstimedate = date('Y-m-d H:i',$etimepre2);

            //获取预定当天 结束时间 0 点 6点 时间
            $etime0 = strtotime(date("Y-m-d 00:00:00",strtotime($etime)));
            $etime6 = $etime0 + 3600*6;
            $etime12 = $etime0 + 3600*12;
            $etime36 = $etime0 + 3600*36;

        }else{

            if($timing == 1 || $timing == 0){
                $this->error("请选择结束时间");
            }

            //和预定当天6点时间比较
            if($stimepre < $stime6){
                $etime = $stime12;
            }else{
                $etime = $stime36;
            }
            $outstimedate = date('Y-m-d H:i',$etime);

        }

        //无结束日期的小时房 强制到 12点或者次日12点
        if($timing == '2'){
            //和预定当天6点时间比较
            if($stimepre < $stime6){
                $etime = $stime12;
            }else{
                $etime = $stime36;
            }
            $outstimedate = date('Y-m-d H:i',$etime);

        }

        //最终的时间
        $stime0 = strtotime(date("Y-m-d",strtotime($stime)));
        $stime24 = strtotime(date("Y-m-d 23:59:59",strtotime($stime)));
        //没有结束日期 timing = 2
        if($timing == '2'){
            $etime0 = strtotime(date("Y-m-d",$etime));
            $etime24 = strtotime(date("Y-m-d 23:59:59",$etime));

        }else{
            $etime0 = strtotime(date("Y-m-d",strtotime($etime)));
            $etime24 = strtotime(date("Y-m-d 23:59:59",strtotime($etime)));
        }


        if(empty($rid)){
            $this->error("房间参数错误");
        }
        $rinfo = db("house")->where(['id'=>$rid])->field("id,h_title as title,h_id as hid,h_attr as attr,h_status,h_statusText,h_stock,h_price,h_weekprice,h_allprice as allprice,h_depositroom")->find();

        if(!$rinfo){
            $this->error("房间数据错误");
        }else{
            if($rinfo['h_status'] != "normal"){
                $this->error("房间已下架");
            }


            $olist = db("order")
                ->where(["room_id"=>$rinfo['id']])
                ->where("pay_status='1' || pay_status='2'")
                ->where("stime >= '$stime0' && etime <= '$etime24' || etime >='$stime0' && stime <= '$stime0' || etime >= $stime0 && stime <= $etime24")
                ->field("id,room_id,stime,etime,pay_status")
                ->select();
            if($olist){
                $this->error("该房间在您预定的时间内被预定了，请换个时间");
            }

            unset($rinfo['h_status']);

            unset($rinfo['h_stock']);
            //酒店信息
            $hinfo = db("hotels")->where(['hid'=>$rinfo['hid']])->field("h_phone")->find();

            //动态价格 是小时价 (小时价要考虑是否是周末价或者活动价) 还是 全天价

            //判断是否有日历价格
            $price = "0.0";
            $preprice = "0.0";
            $where["starttime"] = $stime0;
            $where["f_id"] = $rinfo["id"];
            $rdata = db("calendar")->where($where)->find();

            if($rdata){
                $preprice = $price = sprintf("%1\$.2f",$rdata["title"]);
            }else{
                //判断是否取周末价
                if($w == 5 || $w == 6){
                    if($rinfo["h_weekprice"] != 0){
                        $preprice = $price = sprintf("%1\$.2f",$rinfo["h_weekprice"]);
                    }else{
                        $preprice = $price = $rinfo['h_price'];
                    }
                }else{
                    $preprice = $price = $rinfo['h_price'];
                }
            }
            unset($rinfo['h_weekprice']);

            if($timing == 2){ //小时房 无结束日期

                $rinfo['deposit'] =  $rinfo['h_depositroom'];
                $text = "入住时间：".$instimedate."，最迟离店时间：".$outstimedate."，如果提前办理，请联系电话：".$hinfo['h_phone'];
                $money = sprintf("%1\$.2f",$rinfo["deposit"]);
                $explain = "计费开始时间:".$instimedate.",计费截止时间：".$outstimedate."，不确定结束日期，默认12点，需要预付押金：". $rinfo['deposit']."元，";
                $rinfo['hourlong'] = "不确定";

            }elseif ($timing == 1){ //小时房 有结束日期
                $rinfo['deposit'] = "0.0";
                $totalprice = $rinfo['allprice'];

                $overday = getDatediffeday($instimedate,$outstimedate);//相差天

                if($overday == 1){
                    $dayhour = 24;
                }else{
                    $dayhour = 0;
                }

                $nowmin = getDatediffemin($instimedate,$outstimedate);//相差分钟数
                $nowhour2 = $nowhour =  floor($nowmin/60);//取小时数
                $overmine2 = $nowmin%60;//取分钟余数

                if($overmine2 >= $overmine){ //如果余数超过了允许超过分钟换做小时的配置
                    $nowhour2 ++;
                }

                $nowhour = $dayhour + $nowhour;
                $nowhour2 = $dayhour + $nowhour2;


                $hour = $nowhour;
                $min = $overmine2;
                $money = $price * $nowhour2;
                $rinfo['hourlong'] = $nowhour2."小时";

                if($money>$totalprice){
                    $money = $totalprice;
                }

                $text = "入住时间：".$instimedate."，最迟离店时间：".$outstimedate."，如果提前办理，请联系电话：".$hinfo['h_phone'];
                $explain = "计费开始时间:".$instimedate.",计费截止时间：".$outstimedate.",小时数：".$nowhour.",超出分钟数：".$overmine2.",平台限定".$overmine."分钟，按照一小时计费，小时房超过封顶价按照全日房费收取，本次小时数：".$nowhour2."小时，房费：".$money."元，";

            }else{ //全天房费

                $instimedate0 = date("Y-m-d H:i",$stime0);
                //如果是6点到下午2点之前预定的全日房 入住时间都是下午14点
                if($system0 == $stime0 && $system0 == $etime0){
                    $instimedate =  date("Y-m-d H:i",$stime14);
                }else{
                    $instimedate =  date("Y-m-d 14:00",$stime0);
                }

                $outstimedate0 = date("Y-m-d H:i",$etime0);
                $outstimedate = date("Y-m-d H:00",$etime12);
                $overday = getDatediffeday($instimedate0,$outstimedate0);//相差天
                //如果是凌晨0-6点 这里计算为0天 默认写一天
                if($overday == 0){
                    $overday = 1;
                }
                $rinfo['hourlong'] = $overday."天";

                $rinfo['deposit'] = "0.0";
                $price = $rinfo['allprice'];
                $money = $rinfo['allprice'] * $overday;

                $explain = "全天费用，入住时间:".$instimedate.",离店时间：".$outstimedate.",天数：".$overday."天，房费：".$money."元，";
                $text = "入住时间".$instimedate."，离店时间".$outstimedate."，如果提前办理，请联系电话：".$hinfo['h_phone'];
            }

            //unset($rinfo['allprice']);
            unset($rinfo['h_price']);
            $rinfo["price"] = $price;

            unset($rinfo['h_depositroom']);

            //基础服务费
            $res2 = model('Config')->where("name='baseprice'")->field("value")->find();
            $bprice = "0.0";
            if($res2){
                $restmp = $res2->toarray()["value"];
                $orderbase = json_decode($restmp,true);
                $bprice = $orderbase["基础费用"];
                $amoney = (float)$money+(float)$bprice;
                $explain .= "基础服务费：".$bprice."元,共计：".$amoney."元";
            }else{
                $explain .= "基础服务费：0元,共计：".$money."元";
            }

            $rinfo["bprice"] = sprintf("%1\$.2f",$bprice);
            $res['room'] = $rinfo;
            $m = sprintf("%1\$.2f",$money) + $rinfo["bprice"];
            $res['money'] = sprintf("%1\$.2f",$m);

        }



        $res['preprice'] = $preprice;
        $res['timing'] = $timing;
        $res['text'] = $text;
        if($timing ==0){
            $res['stimepre'] = strtotime($instimedate);
        }else{
            $res['stimepre'] = $stimepre;
        }

        $res['stime'] = strtotime($instimedate);
        $res['etime'] = strtotime($outstimedate);
        $res['hour'] = $hour;
        $res['min'] = $min;
        $res['tip1'] = "押金补充说明";
        $res['tip2'] = "基础服务费补充说明";
        $res['costexplain'] = $explain;
        return $res;
    }


    //提交订单 暂时为生成订单
    //支付分三种：全日房 不要押金 小时房（如果有结束日期也不要押金） 小时房（未选择结束日期则是全日房费押金）
    //说明：计费规则
    //0.00 - 6.00 当天12点退房
    //6.00 - 24.00 次天12点退房
    //如果是全日房 就考虑常规订房 目前多数城市的酒店是按照国际惯例执行，宾馆的入住时间为14：00，离店时间为正午12：00。按此时段进行入住收取1晚房费。

    //这里留下一个思考：如果用户小时房的费用超过了总房费，则最多扣除总房费，但是理论上 他是可以住到全天的时长，但是这里他选择了结束时间，所以程序就以他选择的时间为准，
    //后续如果有必要，再沟通改变，暂时先以选择时间为准。

    protected function computerOrder20210904($uid,$rid,$timing,$stime,$etime){

        //$timing//全日房或者小时房 0全日房 1小时房（有结束时间） 2小时房（无结束时间）
        //全日房不计算 hour min 等信息 ；小时房（有结束日期）需要开始就记录； 小时房（无结束时间）退房时记录

        //入住时间 动态获取
        $stimepre = strtotime($stime);
        $instime = 0;
        $outtime = 0;
        $overmine = 0;//超过配置分钟 则算作一小时
        $res3 = model('Config')->where("name='ordercofig'")->field("value")->find();
        if($res3){
            $restmp = $res3->toarray()["value"];
            $ordercofig = json_decode($restmp,true);
            $instime = $stimepre + $ordercofig['计费时间'] * 60;
            $outtime = $ordercofig['允许延迟退房'] * 60;
            $overmine = $ordercofig['超分算时'];
        }

        $instimedate = date('Y-m-d H:i',$instime);

        //返回数据
        $res = [];
        $text = "";
        $explain = "";
        $money = 0;
        $hour = 0;
        $min = 0;
        //获取预定当天 开始时间 0 点 6点 时间
        $stime0 = strtotime(date("Y-m-d 00:00:00",strtotime($stime)));
        $stime6 = $stime0 + 3600*6;
        $stime12 = $stime0 + 3600*12;
        $stime14 = $stime0 + 3600*14;
        $stime36 = $stime0 + 3600*36;


        //判断指定日期是周几
        $w = date("w",$stime0);
        if(empty($uid)){
            $this->error("用户参数错误");
        }
        //获取当前用户信息
        $uinfo = db("user")->where(['id'=>$uid])->field("nickName,phone")->find();

        if(!$uinfo){
            $this->error("房间信息错误");
        }

        $res['user'] = $uinfo;

        if($timing == ""){
            $this->error("订房类型不能为空");
        }
        if(!in_array($timing,[0,1,2])){
            $this->error("订房类型不合法");
        }

        if(empty($stime)){
            $this->error("开始时间不能为空");
        }

        //存在结束时间
        if($etime){
            $etimepre = strtotime($etime);

            if(($etimepre - $stimepre) < 7200){
                $this->error("分时房两小时起租！");
            }
            $etimepre2 = $etimepre + $outtime;
            $outstimedate = date('Y-m-d H:i',$etimepre2);

            //获取预定当天 结束时间 0 点 6点 时间
            $etime0 = strtotime(date("Y-m-d 00:00:00",strtotime($etime)));
            $etime6 = $etime0 + 3600*6;
            $etime12 = $etime0 + 3600*12;
            $etime36 = $etime0 + 3600*36;

        }else{
            if($timing == 1 || $timing == 0){
                $this->error("请选择结束时间");
            }

            //和预定当天6点时间比较
            if($stimepre < $stime6){
                $etime = $stime12;
            }else{
                $etime = $stime36;
            }
            $outstimedate = date('Y-m-d H:i',$etime);

        }


        if(empty($rid)){
            $this->error("房间参数错误");
        }
        $rinfo = db("house")->where(['id'=>$rid])->field("id,h_title as title,h_id as hid,h_attr as attr,h_status,h_statusText,h_stock,h_price,h_weekprice,h_allprice as allprice,h_depositroom")->find();

        if(!$rinfo){
            $this->error("房间数据错误");
        }else{
            if($rinfo['h_status'] != "normal"){
                $this->error("房间已下架");
            }

            if($rinfo['h_statusText'] != "reserve" && $rinfo['h_statusText'] != "normal"){
                $this->error("房间暂时不能预定");
            }

            unset($rinfo['h_status']);

            unset($rinfo['h_stock']);
            //酒店信息
            $hinfo = db("hotels")->where(['hid'=>$rinfo['hid']])->field("h_phone")->find();

            //动态价格 是小时价 (小时价要考虑是否是周末价或者活动价) 还是 全天价

            //判断是否有日历价格
            $price = "0.0";
            $preprice = "0.0";
            $where["starttime"] = $stime0;
            $where["f_id"] = $rinfo["id"];
            $rdata = db("calendar")->where($where)->find();

            if($rdata){
                $preprice = $price = sprintf("%1\$.2f",$rdata["title"]);
            }else{
                //判断是否取周末价
                if($w == 5 || $w == 6){
                    if($rinfo["h_weekprice"] != 0){
                        $preprice = $price = sprintf("%1\$.2f",$rinfo["h_weekprice"]);
                    }else{
                        $preprice = $price = $rinfo['h_price'];
                    }
                }else{
                    $preprice = $price = $rinfo['h_price'];
                }
            }
            unset($rinfo['h_weekprice']);

            if($timing == 2){ //小时房 无结束日期

                $rinfo['deposit'] =  $rinfo['h_depositroom'];
                $text = "入住时间：".$instimedate."，最迟离店时间：".$outstimedate."，如果提前办理，请联系电话：".$hinfo['h_phone'];
                $money = sprintf("%1\$.2f",$rinfo["deposit"]);

            }elseif ($timing == 1){ //小时房 有结束日期
                $rinfo['deposit'] = "0.0";

                //动态计算房费  这里有可能超过全天房费 如果超过 则自动切换为全天房费模式；修改，
                $allprice = $rinfo['allprice'];
                $avghour = floor($allprice/$price); //向下取整
                $ovmintime = strtotime($instimedate)+$avghour * 3600; //到切换全天费用的时间节点 时间戳
                // $ovmindate = date("Y-m-d H:i",$ovmintime); //到切换全天费用的时间节点 日期格式

                //如分时带有结束日期的时间 超过了 切换全天费用的时间节点 则自动切换全天默认
                if($etimepre > $ovmintime){
                    $stime = $stime14;
                    $instimedate = date('Y-m-d H:i',$stime);
                    //判断结束时间
                    if($etimepre > $etime12){
                        $etime = $etime36;
                    }else{
                        $etime = $etime12;
                    }
                    $outstimedate = date('Y-m-d H:i',$etime);
                    $overday = getDatediffeday($instimedate,$outstimedate);//相差天
                    $nowday = $overday + 1;
                    $price = $rinfo['allprice'];
                    $money = $price * $nowday;
                    $timing = 0;
                    $text = "入住时间：".$instimedate."，最迟离店时间：".$outstimedate."，如果提前办理，请联系电话：".$hinfo['h_phone'];
                    $explain = "分时计费相当于全天费用，计费模式改成全日房更划算，入住时间:".$instimedate.",离店时间：".$outstimedate.",天数：".$nowday ;

                }else{
                    $nowmin = getDatediffemin($instimedate,$outstimedate);//相差分钟数
                    $nowhour2 = $nowhour =  floor($nowmin/60);//取小时数
                    $overmine2 = $nowmin%60;//取分钟余数
                    if($overmine2 >= $overmine){ //如果余数超过了允许超过分钟换做小时的配置
                        $nowhour ++;
                    }

                    $hour = $nowhour2;
                    $min = $overmine2;
                    $money = $price * $nowhour;
                    $text = "入住时间：".$instimedate."，最迟离店时间：".$outstimedate."，如果提前办理，请联系电话：".$hinfo['h_phone'];
                    $explain = "计费开始时间:".$instimedate.",计费截止时间：".$outstimedate.",小时数：".$nowhour2.",超出分钟数：".$overmine2.",平台限定".$overmine."分钟，按照一小时计费";

                }

            }else{ //全天房费

                $instimedate0 = date("Y-m-d H:i",$stime0);
                $instimedate =  date("Y-m-d H:00",$stime14);
                $outstimedate0 = date("Y-m-d H:i",$etime0);
                $outstimedate = date("Y-m-d H:00",$etime12);
                $overday = getDatediffeday($instimedate0,$outstimedate0);//相差天


                $rinfo['deposit'] = "0.0";
                $price = $rinfo['allprice'];
                $money = $rinfo['allprice'] * $overday;
                $explain = "全天费用，入住时间:".$instimedate.",离店时间：".$outstimedate.",天数：".$overday ;
                $text = "入住时间".$instimedate."，离店时间".$outstimedate."，如果提前办理，请联系电话：".$hinfo['h_phone'];
            }

            //unset($rinfo['allprice']);
            unset($rinfo['h_price']);
            $rinfo["price"] = $price;

            unset($rinfo['h_depositroom']);

            //基础服务费
            $res2 = model('Config')->where("name='baseprice'")->field("value")->find();
            $bprice = "0.0";
            if($res2){
                $restmp = $res2->toarray()["value"];
                $orderbase = json_decode($restmp,true);
                $bprice = $orderbase["基础费用"];
            }

            $rinfo["bprice"] = sprintf("%1\$.2f",$bprice);
            $res['room'] = $rinfo;
            $m = sprintf("%1\$.2f",$money) + $rinfo["bprice"];
            $res['money'] = sprintf("%1\$.2f",$m);

        }

        $res['preprice'] = $preprice;
        $res['timing'] = $timing;
        $res['text'] = $text;
        if($timing ==0){
            $res['stimepre'] = strtotime($instimedate);
        }else{
            $res['stimepre'] = $stimepre;
        }

        $res['stime'] = strtotime($instimedate);
        $res['etime'] = strtotime($outstimedate);
        $res['hour'] = $hour;
        $res['min'] = $min;
        $res['tip1'] = "押金补充说明";
        $res['tip2'] = "基础服务费补充说明";
        $res['costexplain'] = $explain;

        return $res;

    }


    //预览订单数据 未创建订单
    public function preOrder(){
        $uid = $this->request->request("uid");
        $rid = $this->request->request("rid");
        $timing = $this->request->request("timing");
        $stime = $this->request->request("stime");
        $etime = $this->request->request("etime");
        $res = $this->computerOrder($uid,$rid,$timing,$stime,$etime);


        if($timing == "0"){
            $res['room']['unit'] = "元/天";
            $res['room']['priceName'] = "房费";
        }else{
            $res['room']['unit'] = "元/时";
            $res['room']['priceName'] = "时租房";
        }

        $this->success("success",$res);

    }


    //提交订单 创建订单表数据
    /* 规则
     全日房 （微信、余额）
     小时房（微信、余额、小时卡）
     第一根据房间的配置 决定用户是否可以用哪种支付方式
     第二根据用户账户余额，如果全部满足那就可以用，如果不满足 那就只能用微信支付和小时卡支付
     第三小时卡支付，基础服务费和押金部分必须微信支付，小时卡只能抵扣房费
     第四，基于第三点 组合模式只能是 一下几种
     1. 单纯余额支付
     2. 单纯微信支付
     3. 小时卡+微信（这里的微信用来抵扣基础服务费、押金、部分房费）
     小时卡暂时只做单个不支持多个*/

    //这里多一个考虑，如果用户预定的是小时房，需要判断用户选择的开始时间和当前时间比对，考虑用户在支付页面停留时间，自动加上延迟时间 如果开始时间没有到，则不进行延迟加时操作。
    //小时房不能超过次日12点 也就是最多一天 不能超过封顶价 一天按照配置的10小时来计算
    public function craeteOrder(){

        $uid = $this->request->request("uid");
        $rid = $this->request->request("rid");
        $timing = $this->request->request("timing");
        $stime = $this->request->request("stime");

        $prestime = strtotime($stime);//用户提交的开始时间

        $etime = $this->request->request("etime");
        if($etime){
            $preetime = strtotime($etime);//用户提交的结束时间
        }

        //修改信息提交
        //$count = $this->request->request("count",0);//预定房间数量 写固定1 暂时不考虑 本期 不考虑多间预定的情况
        $count = 1;
        $names = $this->request->request("names",'');//住房姓名 以 "/" 分割
        $phones = $this->request->request("phones",'');//住房人电话 以 "/" 分割

        if(empty($count)){
            $this->error("请输入预定房间数量");
        }

        if(!is_numeric($count)){
            $this->error("房间数量必须是数字");
        }

        if(empty($names)){
            $this->error("请输入住房人姓名");
        }
        if(empty($phones)){
            $this->error("请输入手机号");
        }

        $odb = db("order");
        $udb = db('user');
        $rdb = db('house');
        $hdb = db('hotels');

        $timedown = $now = time();

        //判断用户延迟时间 只针对小时房 而且是 预定时间小于当前时间的（也就是判断用户选择的时间和当前系统时间的差）
        if($timing != '0'){
            if($now > $prestime){
                $stime = $now;
            }else{
                $stime = $prestime;
            }
            //结束时间
            if($timing == '1'){
                if($now > $prestime){
                    $moretime = $now - $prestime;
                    $etime = $preetime + $moretime;
                }else{
                    $etime = $preetime;
                }
            }else{
                $etime = strtotime($etime);
            }


        }else{
            $stime = $prestime;
        }

        //提交后30分钟
        $confirm_time30 = $now + 30*60;
        //预定前2小时
        $stime_time2 = $stime - 2*3600;


        $hourDaily = 24;
        $overtimeminute = 0;
        $cancelpay_time = $stime;//免费取消 不扣费时间 改成 根据用户选择的入住时间 而不是当前时间

        $tmpstime = date('Y-m-d 14:00',$cancelpay_time);//针对全日房
        $cancelpay_time0 = $cancelpay_time1 = strtotime($tmpstime);//免费取消 全日房
        if($timing == "0"){
            $stime_time2 = $cancelpay_time0 - 2*3600;
        }


        $moveinto = $now;//计费时间
        $res = model('Config')->where("name='ordercofig'")->field("value")->find();

        if($res){
            $restmp = $res->toarray()["value"];
            $orderbase = json_decode($restmp,true);
            if($orderbase['支付时间']){
                $timedown = $timedown + $orderbase['支付时间'] * 60;
            }else{
                $timedown = $timedown + 20*60;//默认20分钟
            }

            if($orderbase['每天时长']){
                $hourDaily = $orderbase['每天时长'];
            }
            if($orderbase['超分算时']){
                $overtimeminute = $orderbase['超分算时'];
            }
            if($orderbase['免费取消时间']){
                //全日房 再加一个判断，如果预定的是今天，时间已经过去了14点如果之间则自动当前时间进行计算
                $system0 = strtotime(date("Y-m-d",$now));//点前日期零点
                if($timing == '0'){
                    //全日房
                    $cancelpay_time0 = $cancelpay_time0 - $orderbase['免费取消时间'] * 3600;
                    //针对全日房 0-6点 免费取消就是当前
                    $sdate0 = strtotime(date("Y-m-d",$prestime));
                    $edate0 = strtotime(date("Y-m-d",$preetime));
                    if($edate0 == $sdate0){
                        //说明是凌晨预定
                        $cancelpay_time0 = $now;
                    }else{
                        if($system0 == $sdate0){
                            //今天
                            $cancelpay_time0 = $now - $orderbase['免费取消时间'] * 3600;
                        }
                    }

                }else{
                    $cancelpay_time = $cancelpay_time - $orderbase['免费取消时间'] * 3600;
                }
            }


            if($orderbase['计费时间']){
                //全日房 再加一个判断，如果预定的是今天，时间已经过去了14点如果之间则自动当前时间进行计算
                $system0 = strtotime(date("Y-m-d",$now));//点前日期零点

                if($timing == '0'){
                    //针对全日房 0-6点 入住时间就是当前时间
                    $sdate0 = strtotime(date("Y-m-d",$prestime));
                    $edate0 = strtotime(date("Y-m-d",$preetime));
                    if($edate0 == $sdate0){
                        //说明是凌晨预定
                        $moveinto = $now + $orderbase['计费时间'] * 60;
                    }else{
                        if($system0 == $sdate0){
                            //今天
                            $moveinto = $now + $orderbase['计费时间'] * 60;
                        }else{
                            $moveinto = $cancelpay_time1 + $orderbase['计费时间'] * 60;
                        }
                    }
                }else{
                    $moveinto = $stime + $orderbase['计费时间'] * 60;
                }
            }

        }else{
            $timedown = $timedown + 20*60;//默认20分钟
        }


        //订单数据
        $order = [];
        $stime = date("Y-m-d H:i:s",$stime);
        if($timing == '0'){
            $etime = $preetime;
        }

        if($timing != '2'){
            $etime = date("Y-m-d H:i:s",$etime);
        }else{
            $etime = "";
        }

        $res = $this->computerOrder($uid,$rid,$timing,$stime,$etime);

        if($res){
            $rinfo = $rdb->where(['id'=>$rid])->find();
            $hinfo = $hdb->where(['hid'=>$rinfo['h_id']])->field("hoteltitle,h_phone")->find();
            $uinfo = $udb->where(['id'=>$uid])->field("money,hours,phone,nickName")->find();

            //准备返回数据
            $ordernumber = "R".$rid."".$uid."".date("YmdHis", time()) . rand(100000, 999999);
            $resdata['order_number'] = $ordernumber;
            $deposit = $res['room']['deposit'];
            $bprice = $res['room']['bprice'];
            $price = $res['room']['price'];
            $preprice = $res['preprice'];
            //支付方式
            $paystyles = [];
            if($res['timing'] == 0){
                $priceText = "全日房费".$price."元/天";
                $paystyles['yue']['index'] = 1;
                $paystyles['yue']['flag'] = 1;
                $paystyles['yue']['text'] = "";
                $paystyles['yue']['data'] = [];
                $paystyles['wx']['index'] = 0;
                $paystyles['wx']['flag'] = 1;
                $paystyles['wx']['text'] = "";
                $paystyles['xw']['data'] = [];
                $paystyles['xsk']['index'] = 2;
                $paystyles['xsk']['flag'] = 0;
                $paystyles['xsk']['text'] = "";
                $paystyles['xsk']['data'] = [];

            }else{
                $priceText = "时租费".$preprice."元/小时";
                $paystyles['yue']['index'] = 1;
                $paystyles['yue']['flag'] = 1;
                $paystyles['yue']['text'] = "";
                $paystyles['yue']['data'] = [];
                $paystyles['wx']['index'] = 0;
                $paystyles['wx']['flag'] = 1;
                $paystyles['wx']['text'] = "";
                $paystyles['wx']['data'] = [];
                $paystyles['xsk']['index'] = 2;
                $paystyles['xsk']['flag'] = 1;
                $paystyles['xsk']['text'] = "";
                $paystyles['xsk']['data'] = [];
            }

            $maxhour = 0;
            $money = $resdata['money'] = sprintf("%1\$.2f",$res['money'] * $count);

            if($res['timing'] == "2"){
                $resdata['cost_explain'] = "费用说明：押金".$deposit."元，基础服务费".$bprice."元，".$priceText.",费用".$res['money']."元，数量".$count."间,共计".$money."元";
            }else{
                $resdata['cost_explain'] = "费用说明：基础服务费".$bprice."元，".$priceText.",费用".$res['money']."元，数量".$count."间,共计".$money."元";
            }



            $resdata['htitle'] = $hinfo['hoteltitle'];
            $resdata['timedown'] = $timedown;
            $paystyle = $resdata['paystyle'] = $rinfo['h_paysytle'];

            //房间的支付方式 0微信 1 余额 2 小时卡
            if($paystyle){
                $paystylearr = explode(",",$paystyle);
                //微信支付
                if(!in_array(0,$paystylearr)) {
                    $paystyles['wx']['flag'] = 0;
                    $paystyles['wx']['text'] = "该房间不允许微信支付";

                }

                //余额支付
                if(!in_array(1,$paystylearr)) {
                    $paystyles['yue']['flag'] = 0;
                    $paystyles['yue']['text'] = "该房间不允许余额支付";

                }else{
                    //判断余额是否可用
                    if($uinfo['money'] >= $money ){
                        $yuetext = "余额充足，可用余额：".$uinfo['money']."元";
                        $paystyles['yue']['flag'] = 1;
                        $paystyles['yue']['text'] = $yuetext;
                    }else{
                        $yuetext = "余额不足，可用余额：".$uinfo['money']."元,请先进行充值";
                        $paystyles['yue']['flag'] = 0;
                        $paystyles['yue']['text'] = $yuetext;
                    }
                }

                //小时卡支付
                if(!in_array(2,$paystylearr)){
                    $hourtext = "该房间不允许小时卡支付";
                    $paystyles['xsk']['flag'] = 0;
                    $paystyles['xsk']['text'] = $hourtext;
                }else{
                    if($res['timing'] != 0){

                        //判断小时卡是否可用 最多允许的小时数 如果未选择结束日期 根据全日房费和单价进行 最多可用小时的计算 如果能确定最多使用10个小时，可以再次确定修改，暂时不考虑
                        $maxhour = floor($res['room']['allprice']/$res['preprice']);
                        if($res['timing'] == "1"){
                            $maxhour = $res['hour'];
                            if($res['min']>=30){
                                $maxhour ++;
                            }
                        }

                        if($uinfo['hours']){

                            $dkmoney = $res['preprice'] * $maxhour;
                            $hourtext = "本次小时卡可用".$maxhour."小时，小时卡剩余：".$uinfo['hours']."小时，可抵房费".$dkmoney."元,其他费用则微信支付";
                            $paystyles['xsk']['flag'] = 1;
                            $paystyles['xsk']['text'] = $hourtext;
                            $cardlist = db("user_card")->where(['uid'=>$uid,'status'=>1])->field("id,c_id,less_hours")->select();

                            if($cardlist){
                                foreach ($cardlist as &$v){
                                    $cinfo = db("card")->where(['id'=>$v['c_id']])->field("cardname")->find();
                                    unset($v['c_id']);
                                    $v['cardname'] = $cinfo['cardname'];

                                    //如果没有结束日期，预付款不变 还是 基础+押金
                                    if($timing == "2"){
                                        //判断小时卡列表可以抵扣的费用
                                        $v['nowmoney'] = $res['money'];
                                    }else{
                                        //判断小时卡列表可以抵扣的费用
                                        if($v['less_hours']>=$maxhour){
                                            $nowmoney =  $res['money'] - $res['preprice'] * $maxhour;
                                            $v['nowmoney'] = sprintf("%01.2f", $nowmoney);
                                        }else{
                                            $nowmoney =  $res['money'] - $res['preprice'] * $v['less_hours'];
                                            $v['nowmoney'] = sprintf("%01.2f", $nowmoney);
                                        }
                                    }


                                }
                                $paystyles['xsk']['data'] = $cardlist;
                            }

                        }else{
                            $hourtext = "您未购买小时卡,或者小时卡已经使用完,请先购买小时卡";
                            $paystyles['xsk']['flag'] = 0;
                            $paystyles['xsk']['text'] = $hourtext;
                        }
                    }else{
                        $hourtext = "全日房不能使用小时卡支付";
                        $paystyles['xsk']['flag'] = 0;
                        $paystyles['xsk']['text'] = $hourtext;
                    }




                }

            }else{
                $paystyles['yue']['index'] = 1;
                $paystyles['yue']['flag'] = 0;
                $paystyles['yue']['text'] = "";
                $paystyles['yue']['data'] = [];
                $paystyles['wx']['index'] = 0;
                $paystyles['wx']['flag'] = 0;
                $paystyles['wx']['text'] = "";
                $paystyles['wx']['data'] = [];
                $paystyles['xsk']['index'] = 2;
                $paystyles['xsk']['flag'] = 0;
                $paystyles['xsk']['text'] = "";
                $paystyles['xsk']['data'] = [];
            }

            $resdata['preprice'] = $res['preprice'];//方便计算
            $resdata['maxhour'] = $maxhour;//方便计算

            //获取用户的小时卡未使用
            $resdata['paystyle'] = $paystyles;


            //订单数据准备
            $order['order_number'] = $ordernumber;
            $order['number'] = $count;
            $order['title'] = $rinfo['h_title'];
            $order['hotelname'] = $hinfo['hoteltitle'];
            $order['room_id'] = $rid;
            $order['user_id'] = $uid;
            $order['price'] = $res['preprice'];//房间单价（也可能是周末价、活动价）
            $order['totalprice'] = $rinfo['h_allprice'];//房间封顶价
            $order['bprice'] = $res['room']['bprice'];//基础服务费
            $order['ballprice'] = $res['room']['bprice'] * $count;//总基础服务费 多个房间 （多天的情况也是只收取一次基础服务费）
            $order['deposit'] = $res['room']['deposit'] * $count; //总押金（多个房间）
            $order['all_price'] = ($res['money'] - $res['room']['bprice']) * $count; //总房费（去掉基础服务费，多个房间）
            $order['all_money'] = $res['money'] * $count; //总缴纳
            $order['hourDaily'] = $hourDaily; //每天小时数
            $order['overtimeminute'] = $overtimeminute; //超分算时 超过多少分钟算作1小时
            $order['hour'] = $res['hour'];  //分时 小时数
            $order['min'] = $res['min'];  //分时 分钟数
            $order['add_time'] = $now;
            $order['payend_time'] = $timedown;
            $order['moveinto_time'] = $moveinto;
            $order['room_html'] =  json_encode($rinfo);
            $order['timing'] = $res['timing'];
            $order['stime'] = $res['stimepre'];
            $order['etime'] = $res['etime'];
            $order['confirm_time30'] = $confirm_time30;//提交后30分钟
            $order['stime_time2'] = $stime_time2;//预定前2小时
            $order['hotelid'] = $rinfo['h_id'];
            if($timing == "0"){
                //全日房
                $order['cancelpay_time'] = $cancelpay_time0;//免费取消时间 全日房的 免费取消时间
            }else{
                $order['cancelpay_time'] = $cancelpay_time;//免费取消时间
            }

            $order['sendmsg_time'] = $res['etime'] - 600; //房间到期前10分钟发送短信
            $order['h_phone'] = $hinfo['h_phone']; //酒店电话 发送短信需要
            $order['user_phone'] = $uinfo['phone'];
            $order['user_name'] = $uinfo['nickName'];
            $order['order_name'] = $names;
            $order['order_phone'] = $phones;

            if($odb->insertGetId($order)){
                $this->success("订单创建成功",$resdata);

            }else{
                $this->error("订单创建失败");
            }
        }



    }

    //立即支付 更新订单（支付数据等）
    //如果是余额支付，不用唤起支付，直接扣除用户账号前
    //如果是微信支付，和以前一样
    //如果是小时卡支付，也要唤起支付，以及扣除小时数，写入记录
    //备注，支付前只扣除 库存、余额 小时卡 订单支付方式 等数据  余额支付特殊 不走回调 所以会直接扣掉相关数据
    //备注，回调成功后，写入日志，增加效率 收入等数据
    public function payOrder(){

        $uid = $this->request->request("uid");
        $orderNumber = $this->request->request("orderNumber");
        $payStyle = $this->request->request("payStyle","");
        $cid = $this->request->request("cid","");//使用的小时卡id 小时卡支付时必须有值

        if(empty($uid)){
            $this->error("用户参数错误");
        }
        if(empty($orderNumber)){
            $this->error("订单参数错误");
        }

        if($payStyle == ""){
            $this->error("支付方式不能为空");
        }

        $len = strlen($payStyle);

        if($len > 1){
            if(empty($cid)){
                $this->error("小时卡支付,小时卡id不能为空");
            }
        }

        /*  if($payStyle == '2'){
              $this->error("小时卡不能单独使用");
          }*/


        Db::startTrans();
        $now = time();

        $odb = db("order");
        $oinfo = $odb->where(['order_number'=>$orderNumber])->find();

        if($oinfo){
            if($now > $oinfo['payend_time']){
                $this->error('订单支付超时，请取消后重新下单');
            }


            //全日房 只能微信支付和余额支付
            if($oinfo['timing'] == 0 && $payStyle == "0,2" || $oinfo['timing'] == 0 && $payStyle == "2,0"){
                $this->error('全日房不支持小时卡支付');
            }

            //获取用户信息
            $uinfo = db("user")->where(['id'=>$uid])->field("openid,money,hours,nickName,phone,score")->find();
            //酒店信息
            $hinfo = db("hotels")->field("hoteltitle")->where(['hid'=>$oinfo['hotelid']])->find();
            //房间数据
            $rinfo = db("house")->field("id,h_stock,h_sell")->where(['id'=>$oinfo['room_id']])->find();


            //$rnumber = $rinfo['h_stock'];//库存 历史
            $snumber = $rinfo['h_sell'];//销量 历史 回调是改变
            $rsnumber = $snumber + $oinfo['number']; //销量 新
            //增加销量
            $houseup['h_sell'] = $rsnumber;


            //更新订单信息
            $uporder['upd_time'] = $now;
            $uporder['pay_type'] = $payStyle;

            //$price= 0.05 * 100;//测试 一分钱
            $price=$oinfo["all_money"] * 100;  //真实需要支付的金额 小时卡支付要动态微信部分
            $out_trade_no = $oinfo["order_number"];  //订单号
            $openid = $uinfo['openid'];
            $needMoney = $oinfo['all_money'];
            //余额支付  只能单独使用 不走微信 不用回调 所以订单直接进入完成状态
            $ueff = false;
            if($payStyle == '1'){
                //余额支付没有回调，所以这里修改房间状态 考虑到房间显示问题 这里不能修改房间状态
                //$houseup['h_statusText'] = "reserve";
                //更新房间数据
                $reff = db("house")->where(['id'=>$rinfo['id']])->update($houseup);
                if($needMoney > $uinfo['money']){
                    $this->error("付款失败，账号余额不足");
                }
                //用户数据改变 余额
                $umoney = $uinfo['money'];// 余额 old
                $now_money = $umoney - $needMoney;
                $userup['money'] = sprintf("%01.2f", $now_money);
                $userup['updatetime'] = $now;
                //更新用户数据
                $ueff = db("user")->where(['id'=>$uid])->update($userup);

                //订单数据
                $uporder['pay_time'] = $now;
                $uporder['pay_status'] = "1";//已预订

                //唤起支付前 不做日志，回调后写入日志、短信、积分等信息 但这里需要扣除相关的库存、余额等 因为保留20分钟的支付时间 取消或者倒计时结束（程序自动取消，则回退）

                //余额支付 追加 日志
                $moneylog['createtime'] = time();
                $moneylog['user_id'] = $uid;
                $moneylog['nickname'] = $uinfo['nickName'];
                $moneylog['memo'] = "余额付款-".$hinfo['hoteltitle'];
                $moneylog['service_ids'] = $oinfo['order_number'];
                $moneylog['money'] = $needMoney;
                $moneylog['type'] = 1;
                $moneylog['type2'] = 0;
                $moneylog['before'] = $uinfo['money'];
                $moneylog['after'] =  $uinfo['money'] - $needMoney;
                //添加消费日志
                $ulog = db("user_money_log")->insert($moneylog);

                //更新订单数据
                $upeff = db('order')->where(["order_number"=>$out_trade_no])->update($uporder);

                //更新 积分 和 等级

                $score = round($needMoney, 2);
                $newscore = $uinfo["score"] + $score;

                $eff3= updateLevel($newscore,$uid);//更新积分和等级

                if($reff && $ueff && $ulog && $upeff && $eff3){
                    db::commit();

                    //回调成功发送用户短信
                    if($uinfo["phone"]){
                        sendUmsg($uinfo["phone"],$oinfo['h_phone']);
                    }
                    //房间预定成功酒店
                    if($uinfo["phone"] && $uinfo["nickName"]){
                        sendHOmsg($uinfo["phone"],$uinfo["nickName"]);
                    }


                    //订单数据
                    $res= array("prepay_id"=>"","paySign"=>"","nonce_str"=>"","timeStamp"=>"","order_no"=>$out_trade_no,"payStyle"=>"余额支付","money"=>sprintf("%01.2f", $now_money),"order_time"=>date("Y-m-d H:i:s",time()),"hour"=>$uinfo['hours']);

                    $this->success('恭喜您，余额支付成功',$res,11);
                }else{
                    db::rollback();
                    $this->success('支付数据生成失败');
                }

            }else{

                $reff = db("house")->where(['id'=>$rinfo['id']])->update($houseup);
                //以下的日志在回调后添加
                $ueff = true;
                $ulog = true;
                //微信支付
                if($payStyle == '0'){


                }else{

                    //获得小时卡信息
                    $ucinfo = db("user_card")->where(['id'=>$cid])->find();
                    if($ucinfo['less_hours'] == 0){
                        $uporder['cardid'] = 0;
                    }else{
                        $uporder['cardid'] = $cid;
                    }

                    //如果是小时卡&微信支付 则把支付方式变成 原来的 pay_type = 0,2 ,变成 pay_type = 2;
                    $uporder['pay_type'] = 2;

                    //订单最多使用小时数 逻辑 如果订单timing = 1 有结束日期 可以使用小时卡，无结束日期支付时候只能 预估12点 扣掉对应的小时数（也就是全日房费对应的小时数） 否则退房是可能没有了小时卡
                    $lesshour = 0 ;//使用后剩余小时数，用微信付款


                    if($oinfo['timing'] == 1){
                        $maxhour = $oinfo['hour'];
                        if($oinfo['min'] >= 30){
                            $maxhour++;
                        }

                        //无结束日期 去最多应扣掉的小时数， 向上取整 后续根据实际情况回退 这里固定扣除一天最多10小时 配置
                        $confighour = db("config")->field("value")->where(['id'=>37])->find();
                        if($confighour && $confighour['value']){
                            $maxhour2 = $confighour['value'];
                        }else{
                            $maxhour2 = 10;
                        }
                        if($maxhour > $maxhour2){
                            $maxhour = $maxhour2;
                        }

                        $hascard = false;

                    }else {
                        //无结束日期 去最多应扣掉的小时数， 向上取整 后续根据实际情况回退 这里固定扣除一天最多10小时 配置
                        $confighour = db("config")->field("value")->where(['id'=>37])->find();
                        if($confighour && $confighour['value']){
                            $maxhour = $confighour['value'];
                        }else{
                            $maxhour = 10;
                        }
                        $hascard = true;
                        // $maxhour = ceil($oinfo['totalprice'] / $oinfo['price']);
                    }

                    $nowuserhour = $uinfo['hours'];//当前用户用户表的小时卡数量
                    $nowselhour = $ucinfo['less_hours'];//当前用户选择的小时卡记录

                    $usercardup['updatetime'] = $now;

                    if($nowselhour > $maxhour){
                        $moneylog['before'] = $nowselhour;
                        $moneylog['after'] =  $nowselhour - $maxhour;
                        $usercardup['less_hours'] =  $nowselhour - $maxhour;
                        $trueprice = $oinfo["all_money"] - $maxhour * $oinfo['price'];

                    }elseif($nowselhour == $maxhour){
                        $moneylog['before'] = $nowselhour;
                        $moneylog['after'] =  $nowselhour - $maxhour;
                        $usercardup['less_hours'] =  $nowselhour - $maxhour;
                        $usercardup['status'] =  2;//消费使用完
                        $trueprice = $oinfo["all_money"] - $maxhour * $oinfo['price'];

                    }else{
                        //小时卡不足
                        $moneylog['before'] = $nowselhour;
                        $moneylog['after'] =  0; //不足，
                        $lesshour = $maxhour - $nowselhour; //还差的小时数 微信付款
                        $usercardup['less_hours'] = 0;
                        $usercardup['status'] =  2;//消费使用完
                        $trueprice = $oinfo["all_money"] - $nowselhour * $oinfo['price'];
                    }

                    // 小时卡支付要动态微信部分
                    if($trueprice <= 0){
                        $price =  $oinfo["all_money"] * 100;
                    }else{
                        $price = $trueprice * 100;
                    }

                    //更新user_card表
                    // $usceff = db("user_card")->where(['id'=>$cid])->update($usercardup);

                    //用户表小时数变化
                    if($lesshour > 0){
                        $userup['hours'] = $nowuserhour - $maxhour + $lesshour;
                    }else{
                        $userup['hours'] = $nowuserhour - $maxhour;
                    }
                    $userup['updatetime'] = $now;

                    //没有结束日期的小时卡 需要付款 基础+押金
                    if($hascard){
                        $price =  $oinfo["all_money"] * 100;
                    }

                }

                $PrePay = WxPay::PrePay($out_trade_no,$openid,$price);  //统一下单

                //处理支付信息
                if($PrePay['return_code'] == "FAIL"){
                    $this->error($PrePay['return_msg']);
                }elseif ($PrePay['result_code'] == "FAIL"){
                    $this->error($PrePay['err_code_des']);
                }else{
                    if(empty($PrePay["prepay_id"])){
                        $this->error("prepay_id信息错误");
                    }else{
                        $PrePayId=$PrePay["prepay_id"];  // 获取预支付id

                        $PaySign=WxPay::getPaySign($PrePayId,$PrePay["nonce_str"]);
                        if($payStyle == '0'){
                            $res= array("prepay_id"=>$PrePayId,"paySign"=>$PaySign["PaySign"],"nonce_str"=>$PrePay["nonce_str"],"timeStamp"=>$PaySign["timeStamp"],"order_no"=>$out_trade_no,"payStyle"=>"微信支付","money"=>"","order_time"=>date("Y-m-d H:i:s",time()),"hour"=>"");
                        }else{
                            $res= array("prepay_id"=>$PrePayId,"paySign"=>$PaySign["PaySign"],"nonce_str"=>$PrePay["nonce_str"],"timeStamp"=>$PaySign["timeStamp"],"order_no"=>$out_trade_no,"payStyle"=>"小时卡&微信支付","money"=>"","order_time"=>date("Y-m-d H:i:s",time()),"hour"=> $userup['hours']);
                        }

                        //支付成功后修改订单支付金额
                        $upeff = db('order')->where(["order_number"=>$out_trade_no])->update($uporder);
                        $usceff = true;
                        if($reff && $usceff && $ueff && $ulog && $upeff){
                            db::commit();
                            $this->success('支付数据创建成功',$res,12);
                        }else{
                            db::rollback();
                            $this->success('支付数据生成失败');
                        }
                    }
                }


            }




        }else{
            $this->error("订单信息有误");
        }


    }

    //订房支付后的回调
    public function wxxml(){

        //获取返回的xml
        $testxml = file_get_contents("php://input");
        //将xml转化为json格式
        $jsonxml = json_encode(simplexml_load_string($testxml, 'SimpleXMLElement', LIBXML_NOCDATA));
        //转成数组
        $result = json_decode($jsonxml, true);
        if($result){
            //如果成功返回了
            if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
                //写入回调日志
                file_put_contents("wxxml.json",var_export($result,true).PHP_EOL,FILE_APPEND);

                //订单号
                $this->notifyUrl($result['out_trade_no'],$result['sign'],$result['transaction_id'],$result["total_fee"]);

                //进行改变订单状态等操作。。。。
            }
        }
    }

    //支付成功，修改 订单状态 余额支付不会回调，微信支付 和 小时卡+微信支付的回调处理 销量处理 发送短信 增加积分
    public function notifyUrl($out_trade_no,$sign,$transaction_id,$total_fee){
//          public function notifyUrl(){
//
//             $out_trade_no = $this->request->request("order_number");
//             $sign = $this->request->request("sign");
//             $transaction_id = $this->request->request("transaction_id");
//             $total_fee = $this->request->request("total_fee");


        if(empty($out_trade_no)){
            $this->error("参数错误");
        }

        try{
            $info = db('order')->where(['order_number'=>$out_trade_no])->find();

            $uid = $info["user_id"];
            $userinfo = $this->muser->where(["id"=>$uid])->field("id,score,phone,nickName,money,hours")->find();

            $total_fee2 = $total_fee/100;//微信实际支付的金额
            //酒店信息
            $hinfo = db("hotels")->field("hoteltitle")->where(['hid'=>$info['hotelid']])->find();

            //房间数据
            $rinfo = db("house")->field("id,h_stock,h_sell")->where(['id'=>$info['room_id']])->find();

            if($info){

                //开启事物
                Db::startTrans();
                $nowtime = time();

                //判断订单时间 如是今天 将房源状态改成预定
                $orderstime =strtotime(date("Y-m-d",$info['stime']));
                //系统时间
                $systemtime = strtotime(date("Y-m-d",$nowtime));
                /* if($orderstime == $systemtime){
                     //房间变成预定状态
                     $uphouse['h_statusText'] = 'reserve';
                     $uphouse['updatetime'] = $nowtime;
                     $eff0 = db("house")->where(['id'=>$rinfo['id']])->update($uphouse);
                 }else{
                     $eff0 = true;
                 }*/
                $eff0 = true;

                //更新订单 根据用户支付方式判断更新订单内容   jsw add
                //全日房 单纯微信支付

                //微信支付
                $moneylog['createtime'] = $nowtime;
                $moneylog['user_id'] = $uid;
                $moneylog['nickname'] = $userinfo['nickName'];
                $moneylog['type'] = 0;
                $moneylog['type2'] = 0;
                $moneylog['service_ids'] = $out_trade_no;


                if($info['timing'] == 0 && $info['pay_type'] == 0) {
                    //以下的日志在回调后添加
                    $moneylog['money2'] = $total_fee2;
                    $moneylog['money'] = $total_fee2;
                    $moneylog['memo'] = "微信付款-" . $hinfo['hoteltitle'];
                    //添加消费日志
                    $ulog = db("user_money_log")->insert($moneylog);
                    $usceff = true;
                    $ueff = true;

                }else{

                    //微信+小时卡支付
                    $lesshour = 0 ;//选中的小时卡不足，其他房费用微信付款
                    if($info['timing'] == 1){

                        $maxhour = $info['hour'];
                        if($info['min'] >= 30){
                            $maxhour++;
                        }

                        //有结束日期 如果超过10小时 也按照10小时计算
                        //无结束日期 去最多应扣掉的小时数， 向上取整 后续根据实际情况回退 这里固定扣除一天最多10小时 配置
                        $confighour = db("config")->field("value")->where(['id'=>37])->find();
                        if($confighour && $confighour['value']){
                            $maxhour2 = $confighour['value'];
                        }else{
                            $maxhour2 = 10;
                        }
                        if($maxhour > $maxhour2){
                            $maxhour = $maxhour2;
                        }

                    }else{
                        //无结束日期 去最多应扣掉的小时数， 向上取整 后续根据实际情况回退 这里固定扣除一天最多10小时 配置
                        $confighour = db("config")->field("value")->where(['id'=>37])->find();
                        if($confighour && $confighour['value']){
                            $maxhour = $confighour['value'];
                        }else{
                            $maxhour = 10;
                        }
                        //无结束日期 去最多应扣掉的小时数， 向上取整 后续根据实际情况回退
                        //$maxhour = ceil($info['totalprice']/$info['price']);

                    }


                    $nowuserhour = $userinfo['hours'];//当前用户用户表的小时卡数量



                    if($info['cardid'] > 0){
                        $moneylog['type'] = 2;
                        $moneylog['type2'] = 0;

                        $ucinfo = db("user_card")->where(['id'=>$info['cardid']])->find();
                        $nowselhour = $ucinfo['less_hours'];//当前用户选择的小时卡记录
                        $usercardup['updatetime'] = $nowtime;

                        if($nowselhour > $maxhour){
                            $moneylog['money'] = $maxhour;
                            $moneylog['before'] = $nowselhour;
                            $moneylog['after'] =  $nowselhour - $maxhour;
                            $usercardup['less_hours'] =  $nowselhour - $maxhour;
                            $money2 = $total_fee2;
                            if($money2 >= 0){
                                $moneylog['money2'] = $money2;
                            }else{
                                $moneylog['money2'] = 0;
                            }
                            $odata['wx_income'] = $money2;
                            $odata['use_hour'] = $maxhour;

                        }elseif($nowselhour == $maxhour){
                            $moneylog['before'] = $nowselhour;
                            $moneylog['after'] =  $nowselhour - $maxhour;
                            $moneylog['money'] = $maxhour;
                            $money2 = $total_fee2;
                            if($money2 >= 0){
                                $moneylog['money2'] = $money2;
                            }else{
                                $moneylog['money2'] = 0;
                            }
                            $odata['wx_income'] = $money2;
                            $odata['use_hour'] = $maxhour;
                            $usercardup['less_hours'] =  $nowselhour - $maxhour;
                            $usercardup['status'] =  2;//消费使用完
                        }else{
                            //小时卡不足
                            $moneylog['before'] = $nowselhour;
                            $moneylog['after'] =  0; //不足，
                            $moneylog['money'] = $nowselhour;
                            $lesshour = $maxhour - $nowselhour; //还差的小时数 微信付款
                            $money2 = $total_fee2 + $info['price'] * $lesshour;
                            if($money2 >= 0){
                                $moneylog['money2'] = $money2;
                            }else{
                                $moneylog['money2'] = 0;
                            }

                            $usercardup['less_hours'] = 0;
                            $usercardup['status'] =  2;//消费使用完
                            $odata['wx_income'] = $money2;
                            $odata['use_hour'] = $nowselhour;
                        }

                        //更新user_card表
                        $usceff = db("user_card")->where(['id'=>$info['cardid']])->update($usercardup);

                        //用户表小时数变化
                        if($lesshour > 0){
                            $userup['hours'] = $nowuserhour - $maxhour + $lesshour;
                        }else{
                            $userup['hours'] = $nowuserhour - $maxhour;
                        }
                        $userup['updatetime'] = $nowtime;
                        //更新用户数据
                        $ueff = db("user")->where(['id'=>$uid])->update($userup);


                        if($lesshour > 0){
                            $moneylog['extra'] = $money2;//微信付款金额 不是指支付的金额
                            $mh = $maxhour-$lesshour;
                            $moneylog['remark'] = "小时卡抵扣".$mh."小时，微信付款". $moneylog['extra']."元";
                        }else {
                            $moneylog['extra'] =  $money2; //微信付款金额 不是指支付的金额
                            $moneylog['remark'] = "小时卡抵扣".$maxhour."小时，微信付款". $moneylog['extra']."元";
                        }

                        //小时卡支付+微信支付
                        $moneylog['memo'] = "小时卡&微信支付-".$hinfo['hoteltitle'];
                        //添加消费日志
                        $ulog = db("user_money_log")->insert($moneylog);
                    }else{
                        $moneylog['before'] = 0;
                        $moneylog['after'] =  0; //不足，
                        $moneylog['money'] = $total_fee2;
                        //以下的日志在回调后添加
                        $moneylog['money2'] = $total_fee2;
                        $moneylog['memo'] = "微信付款-" . $hinfo['hoteltitle'];
                        $moneylog['extra'] =  $total_fee2; //微信付款金额
                        $moneylog['remark'] = "微信付款". $total_fee2."元";
                        //添加消费日志
                        $ulog = db("user_money_log")->insert($moneylog);

                        $usceff = true;
                        $ueff = true;
                    }

                }

                //小时房 支付成功后  先预先扣除小时数
                $odata["pay_time"] = $nowtime;
                $odata["pay_status"] = "1";
                $odata["upd_time"] = $nowtime;
                $odata["transaction_id"] = $transaction_id;
                $odata["sign"] = $sign;

                //支付成功 更新 积分 和 等级

                $score = round($total_fee/100, 2);
                $newscore = $userinfo["score"] + $score;
                $eff3= updateLevel($newscore,$uid);//更新积分和等级
                $eff1 = $this->morder->where("id={$info['id']}")->update($odata);

                if($eff0 && $eff1 && $ulog && $eff3 && $usceff && $ueff){
                    Db::commit();
                    //回调成功发送用户短信
                    if($userinfo["phone"]){
                        sendUmsg($userinfo["phone"],$info['h_phone']);
                    }
                    //房间预定成功酒店
                    if($userinfo["phone"] && $userinfo["nickName"]){
                        sendHOmsg($userinfo["phone"],$userinfo["nickName"]);
                    }

                    echo 'success';die;
                }else{
                    Db::rollback();
                    echo 'error';die;
                }

            }else{

                $this->error("数据获取失败");
            }


        }catch (\think\exception\PDOException $e){
            $this->error($e->getMessage());
        }

    }

    //临时退款接口 手动操作 套餐
    public function tuikuanactivity(){
        $order_number = $this->request->request("orderNumber");
        $info = db("orderactivity")->where(['order_number'=>$order_number])->find();

        if($info){
            $allmoney = $info["price"];
            $rtmoney = $info['price'];
            $refund_number = "R".$info['user_id'].date("YmdHis", time()) . rand(100000, 999999);
            $refundRes = $this->submitDrawBackFun($allmoney,$rtmoney ,$info["order_number"],$refund_number,$info["transaction_id"],$info['user_id']);
            //#todo 这里理论上还应该考虑 退款后 积分回退的逻辑，暂时先不考虑
            if ($refundRes['RETURN_CODE'] == 'SUCCESS' && $refundRes['RESULT_CODE'] == 'SUCCESS') {
                print_r($refundRes);
            }else{
                print_r($refundRes);
            }


        }else {
            $this->error("未找到订单");
        }
    }


    //临时退款接口 手动操作 购卡订单
    public function tuikuancard(){
        $order_number = $this->request->request("orderNumber");
        $info = db("user_card")->where(['order_number'=>$order_number])->find();

        if($info){


            $allmoney = $info["c_price"];
            $rtmoney = $info['c_price'];


            $refund_number = "R".$info['uid'].date("YmdHis", time()) . rand(100000, 999999);
            $refundRes = $this->submitDrawBackFun($allmoney,$rtmoney ,$info["order_number"],$refund_number,$info["transaction_id"],$info['uid']);
            //#todo 这里理论上还应该考虑 退款后 积分回退的逻辑，暂时先不考虑
            if ($refundRes['RETURN_CODE'] == 'SUCCESS' && $refundRes['RESULT_CODE'] == 'SUCCESS') {
                print_r($refundRes);
            }else{
                print_r($refundRes);
            }


        }else {
            $this->error("未找到订单");
        }
    }

    //临时退款接口 手动操作 充值订单
    public function tuikuancz(){
        $order_number = $this->request->request("orderNumber");
        $info = db("chongzhi")->where(['code2'=>$order_number])->find();

        if($info){


            $allmoney = $info["money"];
            $rtmoney = $info['money'];


            $refund_number = "R".$info['uid'].date("YmdHis", time()) . rand(100000, 999999);
            $refundRes = $this->submitDrawBackFun($allmoney,$rtmoney ,$info["code2"],$refund_number,$info["code1"],$info['uid']);
            //#todo 这里理论上还应该考虑 退款后 积分回退的逻辑，暂时先不考虑
            if ($refundRes['RETURN_CODE'] == 'SUCCESS' && $refundRes['RESULT_CODE'] == 'SUCCESS') {
                print_r($refundRes);
            }else{
                print_r($refundRes);
            }


        }else {
            $this->error("未找到订单");
        }
    }

    //临时退款接口 手动操作 房源订单888888888888888888
    public function tuikuan(){
        $order_number = $this->request->request("orderNumber");
        $info = db("order")->where(['order_number'=>$order_number])->find();

        if($info){
            $allmoney = $info["all_money"];
            $rtmoney = $info['wx_income'];


            $refund_number = "R".$info['user_id'].date("YmdHis", time()) . rand(100000, 999999);
            $refundRes = $this->submitDrawBackFun($allmoney,$rtmoney ,$info["order_number"],$refund_number,$info["transaction_id"],$info['user_id']);
            //#todo 这里理论上还应该考虑 退款后 积分回退的逻辑，暂时先不考虑
            if ($refundRes['RETURN_CODE'] == 'SUCCESS' && $refundRes['RESULT_CODE'] == 'SUCCESS') {
                print_r($refundRes);
            }else{
                print_r($refundRes);
            }


        }else {
            $this->error("未找到订单");
        }
    }


    //取消订单 如果超过了 取消时间 则扣费用 比例*房源总价格 积分本版本 暂时不考虑回退
    public function cancelOrder(){

        $order_number = $this->request->request("orderNumber");

        $uid = $this->request->request("uid");


        if(empty($order_number) || empty($uid)){
            $this->error("参数错误");
        }
        $where["user_id"] = $uid;
        $where["order_number"] =$order_number;
        //获取订单信息
        $info = $this->morder->where($where)->find();


        //酒店信息
        $hinfo = db("hotels")->where(['hid'=>$info['hotelid']])->field("hid,hoteltitle")->find();
        //房间数据
        $rinfo = db("house")->field("id,h_stock,h_sell")->where(['id'=>$info['room_id']])->find();


        //获取用户信息
        $userinfo = db("user")->where(['id'=>$uid])->find();

        Db::startTrans();

        if($info){
            //根据订单状态判断操作
            if($info["pay_status"] == 0){ //未支付订单取消 退款额 为 总付款 （基础保障费 + 押金 + 房费）不用执行退款
                $updata["pay_status"] = "4";
                $updata["cancel_time"] = time();
                $updata["income"] = 0;//收入为 0
                $updata["return_money"] = $info['all_money'];

                $eres = db("order")->where(['id'=>$info['id']])->update($updata);

                if($eres){
                    Db::commit();
                    $this->success("订单取消成功");
                }else{
                    DB::rollback();
                    $this->error("订单取消失败");
                }



            }elseif($info["pay_status"] == 1){

                //判断是否在允许范围内取消
                $confirm_time30 = $info["confirm_time30"];//全局免费30分钟免费取消

                $cancelpay_time =  $info["cancelpay_time"]; //时间和 $stime_time2 一样
                $time = time();
                //订单数据
                $updata["pay_status"] = "4";
                $updata["cancel_time"] = $time;
                $discount = 0;

                //收费
                $res = model('Config')->where("name='ordercofig'")->field("value")->find();
                if ($res) {
                    $restmp = $res->toarray()["value"];
                    $discount2 = json_decode($restmp, true);
                    if($discount2['取消扣费比例']){
                        $discount = $discount2['取消扣费比例'];
                    }

                }

                //房源数据回归 销量 库存 是否预定

                //$rnumber = $rinfo['h_stock'];//库存 历史
                $snumber = $rinfo['h_sell'];//销量 历史 回调是改变

                // $houseup['h_stock'] = $rnumber + $info['number']; //库存 新
                $houseup['updatetime'] = $time;
                $houseup['h_sell'] = $snumber + $info['number']; //销量 新


                //判断是否改变房间预定状态，如果只有一个预定，那就是当前这个订单，取消后，房源回归
                $count = db("order")->where(['room_id'=>$rinfo['id'],"pay_status"=>"1"])->count();

                if($count == 1){
                    $houseup['h_statusText'] = "normal";//房间回归空闲
                }

                //更新房间数据
                $eff1 = db("house")->where(['id'=>$rinfo['id']])->update($houseup);

                //余额支付 如果未超时 直接退回，如果超时，扣除比例 不走微信
                if($info['pay_type'] == 1){
                    $money = 0;//扣费金额
                    //余额支付 回退余额 追加 日志
                    $moneylog['createtime'] = $time;
                    $moneylog['type'] = 1;
                    $moneylog['type2'] = 1;//退回
                    $moneylog['user_id'] = $uid;
                    $moneylog['nickname'] = $userinfo['nickName'];
                    $moneylog['memo'] = "余额退款-".$hinfo['hoteltitle'];
                    $moneylog['service_ids'] = $info['order_number'];
                    //超过时间，返回减少 计算收益
                    //先进行30分钟时间的判断$confirm_time30


                    if($time > $confirm_time30){

                        //在判断是否在预定前2小时
                        if($time > $cancelpay_time) {

                            if ($discount) {
                                $money = $info["all_money"] * $discount; //扣除已付款的金额的比例 不是房间封顶价的比例
                                $money = sprintf("%01.2f", $money);
                            }
                            $remoney = $info['all_money'] - $money;
                            if($remoney <0){
                                $remoney = 0;
                            }
                            $moneylog['after'] =  $userinfo['money'] + $remoney;
                            $moneylog['money'] = sprintf("%01.2f", $remoney);
                            $moneylog['remark'] = "支付金额".$info['all_money']."元，超时取消，扣除费用".$money."元";

                            $updata['return_money'] = $remoney;//退款金额
                            $updata['income'] = $money;//扣除的费用就是收入


                        }else{

                            $updata['return_money'] = $info['all_money'];//退款金额
                            $moneylog['after'] =  $userinfo['money'] + $info['all_money'];
                            $moneylog['money'] = sprintf("%01.2f", $info['all_money']);
                            $updata['income'] = 0;//收入为0
                        }

                    }else{
                        //只要在30分钟内就免费取消
                        $updata['return_money'] = $info['all_money'];//退款金额
                        $moneylog['after'] =  $userinfo['money'] + $info['all_money'];
                        $moneylog['money'] = sprintf("%01.2f", $info['all_money']);
                        $updata['income'] = 0;//收入为0
                    }



                    $moneylog['before'] = $userinfo['money'];

                    //添加消费日志
                    $eff2 = db("user_money_log")->insert($moneylog);
                    //修改账户余额 余额
                    $usermoney["money"] = $moneylog['after'];
                    $usermoney['updatetime'] = time();
                    $eff3 = db("user")->where(['id'=>$uid])->update($usermoney);

                    //更新订单数据
                    //余额支付 自动退款成功
                    $updata["refund_status"] = 3;//已退款
                    $eff4 = $this->morder->where("id={$info['id']}")->update($updata);

                    if($eff1 && $eff2 && $eff3 && $eff4){
                        //取消成功后发送短信
                        //发送酒店
                        if($info["h_phone"] && $info["user_name"]){
                            sendmsgHCancel($info["h_phone"],$info["user_name"],$money);
                        }
                        //发送给用户
                        if($info["order_phone"] && $info["h_phone"]){
                            sendmsgUCancel($info["order_phone"],$money,$info["h_phone"]);
                        }

                        Db::commit();
                        $this->success("订单取消成功,退款成功，请核实");
                    }else{
                        Db::rollback();
                        $this->error("订单取消失败");
                    }

                }else{

                    $moneylog['type'] = 0;
                    $moneylog['type2'] = 1;

                    //微信支付 和 小时卡支付（微信支付） 走微信退款
                    $remoney = 0;//微信退款金额
                    $money = 0;//扣费金额
                    if($info['pay_type'] == "0"){

                        //微信支付 回退 追加 日志
                        $moneylog['createtime'] = $time;
                        $moneylog['user_id'] = $uid;
                        $moneylog['nickname'] = $userinfo['nickName'];
                        $moneylog['memo'] = "微信退款-".$hinfo['hoteltitle'];
                        $moneylog['service_ids'] = $info['order_number'];


                        if($time > $confirm_time30){
                            //在判断是否在预定前2小时
                            if($time > $cancelpay_time) {
                                if ($discount) {
                                    $money = $info["all_money"] * $discount;
                                    $money = sprintf("%01.2f", $money);
                                }

                                $remoney = $info['all_money'] - $money;

                                if($remoney <0){
                                    $remoney = 0;
                                }
                                //  $moneylog['after'] =  $userinfo['money'] + $remoney;
                                $moneylog['money'] = sprintf("%01.2f", $remoney);
                                $moneylog['remark'] = "支付金额".$info['all_money']."元，超时取消，扣除费用".$money."元";
                                $updata['income'] = $money;
                                $updata['return_money'] = $remoney;//退款金额

                            }else{
                                $remoney = $info['all_money'];
                                $moneylog['money'] = sprintf("%01.2f", $info['all_money']);
                                $updata['income'] = 0;
                                $updata['return_money'] = $info['all_money'];//退款金额
                            }

                        }else{
                            //只要在30分钟内就免费取消
                            $remoney = $info['all_money'];
                            $moneylog['money'] = sprintf("%01.2f", $info['all_money']);
                            $updata['income'] = 0;
                            $updata['return_money'] = $info['all_money'];//退款金额
                        }

                        //添加消费日志
                        $eff2 = db("user_money_log")->insert($moneylog);

                        $eff3 = true;
                        //准备退款数据
                        //执行退款
                        $updata["upd_time"] = $time;
                        $refund_number = "R".date("YmdHis", time()) . rand(100000, 999999);
                        $updata["refund_number"] = $refund_number;

                        if($remoney > 0){
                            $updata["refund_status"] = 2;//申请退款中
                            //更新订单数据
                            $eff4 = $this->morder->where("id={$info['id']}")->update($updata);
                            $refundRes = $this->submitDrawBackFun($info["all_money"],$remoney ,$info["order_number"],$refund_number,$info["transaction_id"],$info['user_id']);
                            file_put_contents("refund.json",var_export($refundRes,true).PHP_EOL,FILE_APPEND);

                            //#todo 这里理论上还应该考虑 退款后 积分回退的逻辑，暂时先不考虑
                            if ($refundRes['RETURN_CODE'] == 'SUCCESS' && $refundRes['RESULT_CODE'] == 'SUCCESS') {
                                file_put_contents("refundsuc.json",var_export($refundRes,true));
                                //退款成功 修改订单状态
                                $updata2["refund_status"] = 3;
                                $updata2["pay_status"] = "4";//已经取消
                                $updata2["return_money"] = $remoney;
                                $updata2["upd_time"] = time();
                                $rincome = $info['all_money'] - $remoney;
                                if($rincome>0){
                                    $updata2["income"] = $info['all_money'] - $remoney; //退款超时导致的百分比收入
                                }else{
                                    $updata2["income"] = 0;
                                }

                                $eff5 = db("order")->where(["id"=>$info["id"]])->update($updata2);

                                if($eff1 && $eff2 && $eff3 && $eff4 && $eff5){
                                    Db::commit();
                                    $this->success("订单取消成功,退款成功，请核实");

                                    //取消成功后发送短信
                                    //发送酒店
                                    if($info["h_phone"] && $info["user_name"]){
                                        sendmsgHCancel($info["h_phone"],$info["user_name"],$money);
                                    }
                                    //发送给用户
                                    if($info["order_phone"] && $info["h_phone"]){
                                        sendmsgUCancel($info["order_phone"],$money,$info["h_phone"]);
                                    }


                                }else{
                                    Db::rollback();
                                    $this->error("订单取消失败");
                                }

                            }else{
                                file_put_contents("refunderr.json",var_export($refundRes,true).PHP_EOL,FILE_APPEND);
                                $msg = "退款失败";
                                Db::rollback();
                                $this->error($msg);
                            }



                        }else{
                            $updata["refund_status"] = 1;//抵消 不走退款

                            //更新订单数据
                            $eff4 = $this->morder->where("id={$info['id']}")->update($updata);

                            if($eff1 && $eff2 && $eff3 && $eff4){
                                //取消成功后发送短信
                                //发送酒店
                                if($info["h_phone"] && $info["user_name"]){
                                    sendmsgHCancel($info["h_phone"],$info["user_name"],$money);
                                }
                                //发送给用户
                                if($info["order_phone"] && $info["h_phone"]){
                                    sendmsgUCancel($info["order_phone"],$money,$info["h_phone"]);
                                }

                                Db::commit();
                                $this->success("订单取消成功，支付的金额刚好抵扣超时取消，无需退款");
                            }else{
                                Db::rollback();
                                $this->error("订单取消失败");
                            }

                        }



                    }else{

                        //小时卡+微信支付
                        $moneylog['type'] = 2;
                        $moneylog['type2'] = 1;

                        //小时卡支付（微信支付） 小时卡退回 微信扣费
                        //小时卡+微信支付 回退 追加 日志
                        $moneylog['createtime'] = $time;
                        $moneylog['user_id'] = $uid;
                        $moneylog['nickname'] = $userinfo['nickName'];
                        $moneylog['memo'] = "小时卡&微信支付-".$hinfo['hoteltitle'];
                        $moneylog['service_ids'] = $info['order_number'];


                        //消费记录表
                        $usermoneydata = db("user_money_log")->where(['user_id'=>$uid,'service_ids'=>$order_number])->find();

                        //用户小时卡表 使用了小时卡
                        if($info['cardid']){
                            $usercarddata = db("user_card")->where(['id'=>$info['cardid']])->find();
                            $less_hours = $usercarddata['less_hours']; //old
                            $ucdataup['less_hours'] = $usermoneydata['money'] + $less_hours; //new
                            $ucdataup['updatetime'] = $time;
                            $ucdataup['status'] = 1;//修改为 未使用完状态
                            $eff2 = db("user_card")->where(['id'=>$info['cardid']])->update($ucdataup);

                            $moneylog['after'] = $usermoneydata['before'] + $usermoneydata['money'];
                            $moneylog['before'] = $usermoneydata['before'];
                            $moneylog['money'] = $usermoneydata['money'];

                        }else{
                            //未使用，虽然用户选择了，但是可能支付时候，没有了小时数
                            $eff2 = true;
                            $moneylog['after'] = $usermoneydata['before'];
                            $moneylog['before'] = $usermoneydata['before'];
                        }


                        if($time > $confirm_time30){
                            //在判断是否在预定前2小时
                            if($time > $cancelpay_time) {
                                if ($discount) {
                                    $money = $usermoneydata["money2"] * $discount;
                                    $money = sprintf("%01.2f", $money);
                                }
                                $remoney = $usermoneydata["money2"] - $money;
                                if($remoney <0){
                                    $remoney = 0;
                                }

                                $moneylog['money2'] = "+".sprintf("%01.2f", $remoney);
                                $moneylog['remark'] = "微信支付".$usermoneydata["money2"]."元，超时取消，小时数返回，微信退款". $remoney ."元，扣费".$money."元";
                                $updata['income'] = $money;
                                $updata['return_money'] = $remoney;//退款金额
                                $updata["use_hour"] =0;
                                $updata["wx_income"] =$money; //退款超时导致的百分比收入

                            }else{
                                $remoney = $usermoneydata['money2']; //微信实际付款
                                $moneylog['money2'] = sprintf("%01.2f", $remoney);
                                $moneylog['remark'] = "微信支付".$moneylog["money2"]."元，小时数退回，微信退款".$moneylog["money2"]."元";
                                $updata['income'] = 0;
                                $updata['return_money'] = $info['all_money'];//退款金额
                                $updata["use_hour"] =0;
                                $updata["wx_income"] =0; //退款超时导致的百分比收入
                            }

                        }else{
                            //只要在30分钟内就免费取消
                            $remoney = $usermoneydata['money2']; //微信实际付款
                            $moneylog['money2'] = sprintf("%01.2f", $remoney);
                            $moneylog['remark'] = "微信支付".$moneylog["money2"]."元，小时数退回，微信退款".$moneylog["money2"]."元";
                            $updata['income'] = 0;
                            $updata['return_money'] = $info['all_money'];//退款金额
                            $updata["use_hour"] =0;
                            $updata["wx_income"] =0; //退款超时导致的百分比收入
                        }


                        //添加消费日志
                        $eff3 = db("user_money_log")->insert($moneylog);
                        $userhours = $userinfo['hours'];
                        //修改账户余额 小时卡
                        $usermoney["hours"] =$userhours + $usermoneydata['money'];
                        $usermoney['updatetime'] = time();
                        $eff4 = db("user")->where(['id'=>$uid])->update($usermoney);

                        //准备退款数据
                        //执行退款
                        $updata["upd_time"] = $time;
                        $refund_number = "refund_".date("YmdHis", time()) . rand(10000000, 99999999);
                        $updata["refund_number"] = $refund_number;

                        if($remoney > 0){
                            $updata["refund_status"] = 2;//申请退款中

                            //更新订单数据
                            $eff5 = $this->morder->where("id={$info['id']}")->update($updata);

                            $refundRes = $this->submitDrawBackFun($usermoneydata['money2'],$remoney ,$info["order_number"],$refund_number,$info["transaction_id"],$info['user_id']);

                            file_put_contents("refund.json",var_export($refundRes,true).PHP_EOL,FILE_APPEND);

                            //#todo 这里理论上还应该考虑 退款后 积分回退的逻辑，暂时先不考虑
                            if ($refundRes['RETURN_CODE'] == 'SUCCESS' && $refundRes['RESULT_CODE'] == 'SUCCESS') {
                                file_put_contents("refundsuc.json",var_export($refundRes,true));
                                //退款成功 修改订单状态
                                $updata2["refund_status"] = 3;
                                $updata2["pay_status"] = "4";//已经取消
                                $updata2["return_money"] = $remoney;
                                $updata2["upd_time"] = time();


                                $eff6 = db("order")->where(["id"=>$info["id"]])->update($updata2);

                                if($eff1 && $eff2 && $eff3 && $eff4 && $eff5 && $eff6){
                                    //取消成功后发送短信
                                    //发送酒店
                                    if($info["h_phone"] && $info["user_name"]){
                                        sendmsgHCancel($info["h_phone"],$info["user_name"],$money);
                                    }
                                    //发送给用户
                                    if($info["order_phone"] && $info["h_phone"]){
                                        sendmsgUCancel($info["order_phone"],$money,$info["h_phone"]);
                                    }

                                    Db::commit();
                                    $this->success("订单取消成功,退款成功，请核实");
                                }else{
                                    Db::rollback();
                                    $this->error("订单取消失败");
                                }

                            }else{
                                file_put_contents("refunderr.json",var_export($refundRes,true).PHP_EOL,FILE_APPEND);
                                $msg = "退款失败";
                                Db::rollback();
                                $this->error($msg);
                            }



                        }else{
                            $updata["refund_status"] = 1;//抵消 不走退款

                            //更新订单数据
                            $eff5 = $this->morder->where("id={$info['id']}")->update($updata);

                            if($eff1 && $eff2 && $eff3 && $eff4 && $eff5){
                                //取消成功后发送短信
                                //发送酒店
                                if($info["h_phone"] && $info["user_name"]){
                                    sendmsgHCancel($info["h_phone"],$info["user_name"],$money);
                                }
                                //发送给用户
                                if($info["order_phone"] && $info["h_phone"]){
                                    sendmsgUCancel($info["order_phone"],$money,$info["h_phone"]);
                                }

                                Db::commit();
                                $this->success("订单取消成功，支付的金额刚好抵扣超时取消，无需退款");
                            }else{
                                Db::rollback();
                                $this->error("订单取消失败");
                            }

                        }


                    }



                }


            }elseif($info['pay_status'] == 2){
                $this->error("您已入住，不能取消");
            }elseif($info['pay_status'] == 3){
                $this->error("订单已完成，不能取消");
            }elseif($info['pay_status'] == 4){
                $this->error("您已经取消了订单！");
            }


        }else{
            $this->error("找不到订单");
        }

    }

    //订单详情 //动态显示退款价格 不做数据库修改，退房后在做最终的修改
    public function orderDetail(){
        $order_number = $this->request->request("orderNumber");
        if(empty($order_number)){
            $this->error("参数错误");
        }
        $now = time();
        $oinfo = db("order")->where(['order_number'=>$order_number])
            ->field("cardid,pay_status,order_number,order_phone,number,order_name,pay_type,overtimeminute,cancelpay_time,moveinto_time,payend_time,add_time,stime,etime,price,checkout_time,totalprice,all_price,deposit,ballprice,all_money,return_money,room_html,room_id,hotelid,hour,min,timing,wx_income,use_hour,confirm_time30,stime_time2")->find();

        $hotelinfo = db("hotels")->field("hoteltitle,h_phone")->where(['hid'=>$oinfo['hotelid']])->find();
        if(empty($hotelinfo)){
            $this->error("酒店信息错误");
        }


        if($oinfo){
            //小时卡 预先扣费的小时卡 显示
            if($oinfo['cardid']){
                //$cardlog = db("user_money_log")->where(['service_ids'=>$oinfo['order_number']])->find();
                //小时卡消费信息
                $oinfo['cardinfo'] = "房间未入住，小时卡抵扣不统计";
            }

            $discount = 0;
            $mhour = 0;
            $mmin = 0;

            //收费
            $res = model('Config')->where("name='discount'")->field("value")->find();
            if ($res) {
                $restmp = $res->toarray()["value"];
                $discount = json_decode($restmp, true);
            }

            //根据订单状态动态显示退款价格
            //未支付
            if($oinfo['pay_status'] == "0" || $oinfo['pay_status'] == "4"){
                $oinfo['all_price'] = 0;//房费默认0

            }
            //预定未入住
            if($oinfo['pay_status'] == "1"){

                if($now > $oinfo['cancelpay_time']){
                    $retmoney = $oinfo['all_money'] * (1-$discount);
                    $oinfo['return_money'] = sprintf("%1\$.2f",$retmoney);
                }else{
                    $oinfo['return_money'] = $oinfo['all_money'];
                }
                $mhour = $hour2 = $oinfo['hour'];
                $mmin = $min = $oinfo['min'];

                //显示免费取消时间
                $oinfo['confirm_time30'] = date("m-d H:i",$oinfo['confirm_time30']);

            }
            //已入住 实时计算退款金额 如果不超过一下 按照最低一小时计费；
            if($oinfo['pay_status'] == "2"){
                //如果是有结束日期 则显示预订的时长 退款为0
                if($oinfo['timing'] == "1"){
                    $mhour = $oinfo['hour'];
                    $mmin = $oinfo['min'];
                    $oinfo['return_money'] = '0.00';
                }elseif($oinfo['timing'] == "0"){
                    $oinfo['return_money'] = '0.00';
                }else{
                    //开始计费时间
                    $mt = $oinfo['moveinto_time'];
                    //总之 无结束日期的小时房 最多不会超过 30个小时 如果就是超过了30小时 也按照 30小时计算
                    $countday = getDatediffedaytemp($mt,$now);
                    $overtimeminute = $oinfo['overtimeminute'];
                    $hour = 0;
                    if($countday == 1){
                        $hour = 24;
                    }
                    $counthour = getDatediffemintemp($mt,$now);
                    $hour2 = floor($counthour/60) + $hour;

                    //判断如时间还未到的情况
                    if($now <= $mt){
                        $mhour = 0;
                        $mmin = 0;
                    }else{
                        $mhour = $hour2;
                        $min = ($counthour - $hour2*60);
                        $mmin = $min;
                        if($min >= $overtimeminute){
                            $hour2++;
                        }
                    }

                    //按照最低一小时收费 //入住的房间 不管什么条件下，如果退房 最少扣除1小时费用
                    if($hour2 <= 0){
                        $hour2 = 1;
                    }

                    //小时卡消费信息
                   // $oinfo['cardinfo'] = "使用小时卡".$hour2."小时，抵扣房费".$oinfo['price']*$hour2."元.";

                    if($hour2>10){
                        $lasthour2 = 10;
                        //小时卡消费信息
                        $oinfo['cardinfo'] = "应扣".$hour2."小时，实扣".$lasthour2."小时.";
                    }else{
                        //小时卡消费信息
                        $oinfo['cardinfo'] = "应扣".$hour2."小时，实扣".$hour2."小时.";
                    }


                    //判断是否需要退款 如果超过了一天的费用 则按照封顶价扣费
                    $price = $oinfo['price'];
                    $number = $oinfo['number'];//预定房间数量

                    $allprice = $price * $hour2;//房费

                    if($allprice >= $oinfo['totalprice']){
                        $allprice = $oinfo['totalprice'];
                    }

                    $yfallprice = $oinfo['all_money'] - $oinfo['ballprice'];//已付费用（包括押金和基础服务费 基础服务费不退）
                    $retrunmoney = $yfallprice - $allprice * $number;

                    $nowprice = $allprice * $number;
                    $oinfo['return_money'] = sprintf("%1\$.2f",$retrunmoney);
                    $oinfo['all_price'] = sprintf("%1\$.2f",$nowprice);
                }

            }elseif($oinfo['pay_status'] == "3"){
                if($oinfo['checkout_time']){
                    $oinfo['checkout_time'] = date("m-d H:i:s",$oinfo['checkout_time']);
                }else{
                    $oinfo['checkout_time'] = "无";
                }
                $mhour = $hour2 = $oinfo['hour'];
                $mmin = $min = $oinfo['min'];
                if($min>=30){
                    $hour2++;
                }
                $money = $hour2 * $oinfo['price'];

                if($hour2>10){
                    $lasthour2 = 10;
                    //小时卡消费信息
                    $oinfo['cardinfo'] = "应扣".$hour2."小时，实扣".$lasthour2."小时.";
                }else{
                    //小时卡消费信息
                    $oinfo['cardinfo'] = "应扣".$hour2."小时，实扣".$hour2."小时.";
                }


            }



            //如果是全日房显示天 小时房显示时长
            if($oinfo['timing'] == 1 || $oinfo['timing'] == 2){
                $oinfo['day'] = $mhour."小时".$mmin."分钟";
            }else{
                $stime = strtotime(date("Y-m-d",$oinfo['stime']));
                $etime = strtotime(date("Y-m-d",$oinfo['etime']));
                $nowday = getDatediffedaytemp($stime,$etime);
                if($nowday == "0"){
                    $nowday = 1;
                }
                $oinfo['day'] = $nowday."天";
            }

            //unset($oinfo['timing']);

            //支付方式
            if($oinfo['pay_type'] == "0"){
                $oinfo['pay_typeText'] = "微信支付";
            }elseif ($oinfo['pay_type'] == 1){
                $oinfo['pay_typeText'] = "余额支付";
            }else{
                $oinfo['pay_typeText'] = "小时卡&微信支付";
            }


            //订单状态
            if($oinfo['pay_status'] == "0"){
                $oinfo['pay_statusText'] = "未支付";
                $oinfo['text'] = "预定入住时间的2小时后至入住时间前扣费15%";
            }elseif ($oinfo['pay_status'] == 1){
                $oinfo['pay_statusText'] = "已预定，待入住";
                $oinfo['text'] = "预定入住时间的2小时后至入住时间前扣费15%";
            }elseif ($oinfo['pay_status'] == 2){
                $oinfo['pay_statusText'] = "已入住";
                $oinfo['text'] = "预定入住时间的2小时后至入住时间前扣费15%";
            }elseif ($oinfo['pay_status'] == 3){
                $oinfo['pay_statusText'] = "已退房";
                $oinfo['text'] = "预定入住时间的2小时后至入住时间前扣费15%";
            }elseif ($oinfo['pay_status'] == 4){
                $oinfo['pay_statusText'] = "已取消";
                $oinfo['text'] = "预定入住时间的2小时后至入住时间前扣费15%";
            }else{
                $oinfo['pay_statusText'] = "支付失败";
                $oinfo['text'] = "预定入住时间的2小时后至入住时间前扣费15%";
            }

            $hinfo = db("hotels")->where(['hid'=>$oinfo['hotelid']])->find();
            $roominfo= json_decode($oinfo["room_html"],true);
            $oinfo['add_time'] = date("Y-m-d H:i",$oinfo['add_time']);
            $oinfo['stime'] = date("m月d日 H:i",$oinfo['stime']);
            $oinfo['etime'] = date("m月d日 H:i",$oinfo['etime']);

            $oinfo['roomInfo']['title'] = $roominfo['h_title'];
            $oinfo['roomInfo']['tip1'] = $roominfo['tip1'];
            $oinfo['roomInfo']['tip2'] = $roominfo['tip2'];
            $oinfo['roomInfo']['housebrand'] = $roominfo['h_housebrand'];
            $oinfo['roomInfo']['img'] = $this->mainhost.$roominfo['h_img'];
            $oinfo['roomInfo']['address'] = $hinfo['h_address'];
            $oinfo['roomInfo']['lng'] = $hinfo['lng'];
            $oinfo['roomInfo']['lat'] = $hinfo['lat'];

            $oinfo['hotelname'] = $hotelinfo['hoteltitle'];
            $oinfo['hotelphone'] = $hotelinfo['h_phone'];

            unset($oinfo['room_html']);

            $this->success("success",$oinfo);
        }else{
            $this->error("订单数据错误");
        }

    }

    //订单列表
    public function myOrderList(){
        $uid = $this->request->request("uid");
        $status = $this->request->request("status","");
        $page = $this->request->request("page",1);
        $limit = $this->request->request("limit",6);
        if(empty($uid)){
            $this->error("参数错误");
        }

        $where = "";
        if($status != "" && $status != 9){
            $where = " pay_status = '$status'";
        }elseif ($status == 9){
            $where = " comment = 0 and pay_status = '3'";
        }


        $count = db("order")
            ->where(['user_id'=>$uid,'userdel'=>0])
            ->where($where)
            ->count();

        $list = db("order")
            ->where(['user_id'=>$uid,'userdel'=>0])
            ->where($where)
            ->field("id,order_number,room_id as rid,stime,etime,pay_status,hotelid,all_money,pay_type,room_html,comment")
            ->page($page,$limit)
            ->order("id desc")
            ->select();

        if($list){
            foreach ($list as &$v){
                $hinfo = db("hotels")->field("hoteltitle")->where(['hid'=>$v['hotelid']])->find();
                $roominfo= json_decode($v["room_html"],true);
                $v['img'] = $this->mainhost.$roominfo['h_img'];
                $stime = $v['stime'];
                $etime = $v['etime'];
                $v['stime'] = date("m月d日",$stime);
                $v['etime'] = date("m月d日",$etime);
                $v['stimehm'] = date("H:i",$stime);
                $v['etimehm'] = date("H:i",$etime);
                $v['sweek'] = getToday($stime);
                $v['eweek'] = getToday($etime);

                $v['title'] = $hinfo['hoteltitle'];
                //订单状态
                if($v['pay_status'] == "0"){
                    $v['pay_statusText'] = "未支付";
                }elseif ($v['pay_status'] == 1){
                    $v['pay_statusText'] = "已预定，待入住";
                }elseif ($v['pay_status'] == 2){
                    $v['pay_statusText'] = "已入住,待结转";
                }elseif ($v['pay_status'] == 3){
                    $v['pay_statusText'] = "已完成";
                }elseif ($v['pay_status'] == 4){
                    $v['pay_statusText'] = "已取消";
                }else{
                    $v['pay_statusText'] = "支付失败";
                }
                unset($v['room_html']);
            }

            $res["rowCount"] = $count;
            $res["pageSize"] = $limit;
            $res["pageIndex"] = $page;
            $res["pageCount"] = ceil($count/$limit);
            $res["rowData"] = $list;

            $this->success("success",$res);
        }else{
            $this->success("暂无记录",[]);
        }
    }

    //删除订单 更新房间和酒店的评分 需要判断用户此时订单状态
    //订单失败，或订单已经取消的 或者 已经完成且已退款完成的  可以 直接删除
    //其他状态订单 删除前必须先取消

    //pay_status  0 未支付 1 已预定（支付） 2 已入住（支付,待退房状态）3 已完成（支付后，退房，房间回归打扫）  4 已取消（未付款，未住，30分钟后，自动取消房间预定，回归空闲，或者后台管理员手动取消，前台用户手动取消） 5支付失败（房间回归空闲）
    //refund_status 0 默认 1 抵消房费(无需退款）2 申请退款 3 已退款 4退款失败
    public function delOrder(){
        $order_number = $this->request->request("orderNumber");
        if(empty($order_number)){
            $this->error("参数错误");
        }
        $oinfo = db("order")->where(['order_number'=>$order_number])->field("id,room_id,hotelid,pay_status,refund_status")->find();

        if($oinfo){
            if($oinfo['pay_status'] == 1){
                $this->error("房间已预定，请取消后删除");
            }
            if($oinfo['pay_status'] == 2){
                $this->error("房间已入住，请退房后删除");
            }
            if($oinfo['pay_status'] == 3){
                if($oinfo['refund_status'] == "2"){
                    $this->error("订单还未退款，请退款后删除");
                }
                if($oinfo['refund_status'] == "4"){
                    $this->error("订单退款失败，请联系客房");
                }
            }

            Db::startTrans();
            $now = time();
            $upd["userdel"] = 1;
            $upd["upd_time"] = $now;
            $eff1 = db("order")->where(['id'=>$oinfo['id']])->update($upd);

            //更新房间
            $cavgpoint = db("comments")->where(['roomid'=>$oinfo['room_id'],'userdel'=>'0'])->avg("goods");
            $cavgpoint = ceil($cavgpoint);
            if($cavgpoint < 1){
                $cavgpoint = 1;
            }elseif ($cavgpoint>5){
                $cavgpoint = 5;
            }
            $rup['h_point'] = $cavgpoint;
            $rup['updatetime'] = $now;

            //更新房间评论
            $eff2 = db("house")->where(['id'=>$oinfo['room_id']])->update($rup);

            $avgpoint = db("house")->where(['h_id'=>$oinfo['hotelid']])->avg("h_point");
            $avgpoint = ceil($avgpoint);
            if($avgpoint < 1){
                $avgpoint = 1;
            }elseif ($avgpoint>5){
                $avgpoint = 5;
            }
            $hup['h_point'] = $avgpoint;
            $hup['updatetime'] = $now;

            //更新酒店评分 酒店评分 = 所有房间评分的平分值
            $eff3 = db("hotels")->where(["hid"=>$oinfo['hotelid']])->update($hup);

            if($eff1 && $eff2 && $eff3){
                Db::commit();
                $this->success("订单删除成功");
            }else{
                Db::rollback();
                $this->error("订单删除失败");
            }
        }else{
            $this->error("订单数据有误");
        }

    }


    /*

    余额支付 ： 全日房 小时房
        只改变订单状态 发送短信  增加收入income

    微信支付 ： 全日房 小时房
        全日房 只改变订单状态 发送短信  增加收入income
        小时房（有结束日期）只改变订单状态 发送短信  增加收入income
        小时房（无结束日期）改变订单状态，发送短信，增加实际收入 押金-实际的费用，退回微信 走微信退款

    小时卡&微信支付
        全日房 无
        小时房
            小时卡充足，扣掉抵扣房费的小时数，退回全部的押金 如果小时卡不够
            如果小时卡不够，扣掉全部小时卡，差价有微信抵扣，退回部分押金
            如果小时卡没有了，押金扣除全部费用，小时卡不变
    */

    //退房（结算）
    public function checkOut(){

        $ordernumber = $this->request->request("orderNumber");
        if(empty($ordernumber)){
            $this->error("订单编号不能为空");
        }


        $odb = db("order");
        $rdb = db("house");
        $labeldb = db("label");
        Db::startTrans();
        //订单信息
        $oinfo =$odb->where(['order_number'=>$ordernumber])->find();

        //用户信息
        $userinfo = db("user")->where(["id"=>$oinfo['user_id']])->field("id,score,phone,nickName,money,hours")->find();

        $houseinfo = json_decode($oinfo['room_html'],true);
        //labels表 休息房、打卡房
        $labels = $houseinfo['h_lebals'];

        //酒店信息
        $hinfo = db("hotels")->where(['hid'=>$oinfo['hotelid']])->find();

        $now = time();
        //订单更新
        $orderup['upd_time'] = $now;

        if($oinfo){
            if($oinfo['pay_status'] == "0"){
                $this->error("订单未支付，无需退房");
            }
            if($oinfo['pay_status'] == "1"){
                $this->error("你还未入住，无需退房");
            }
            if($oinfo['pay_status'] == "3"){
                $this->error("订单已完成，无需操作");
            }
            if($oinfo['pay_status'] == "4"){
                $this->error("订单已取消，无需操作");
            }

            //判断支付方式 余额支付 无需走微信
            if($oinfo['pay_type'] == 1){
                //全日房 和 小时房（有结束日期） 两者情况一样
                if($oinfo['timing'] == "0" || $oinfo['timing'] == "1"){
                    //全日房 支付时 押金和基础服务费和房费都已经付款
                    //退房时 只要修改订单状态就行 无需退款
                    $orderup['pay_status'] = "3";//订单状态
                    $orderup['refund_status'] = 1;//退款状态 抵消费用 无需退款
                    $orderup['return_money'] = 0;// 无需退款 退款金额为0
                    $orderup['income'] = $oinfo['all_money'];//收入等于支付的金额
                    $orderup['checkout_time'] = $now;//退房时间
                    $eff1 = $odb->where(['order_number'=>$ordernumber])->update($orderup);
                    //回归房源状态
                    $rdata["h_statusText"] = "cleaning";
                    $rdata["updatetime"] = $now;
                    $eff2 = $rdb->where("id={$oinfo['room_id']}")->update($rdata);

                    //修改房间属性的数量 修改label表记录
                    if($labels){
                        $number = $oinfo['number'];
                        $eff3 = $labeldb->execute("UPDATE `fa_label` SET `lcount`=`lcount` + $number,`updtime`= $now WHERE  `id` in ($labels) ");
                    }else{
                        $eff3 = true;
                    }

                    if($eff1 && $eff2 && $eff3){
                        Db::commit();
                        if($userinfo["phone"]){
                            //通知用户您入住的房间已经退房
                            //sendCmsg($userinfo["phone"],$houseinfo['h_title']);
                        }
                        if($hinfo["h_phone"]){
                            //通知酒店 用户已经退房，请准时打扫
                            //sendHOmsg($userinfo["phone"],$userinfo["nickName"]);
                        }
                        $this->success("退房成功");
                    }else{
                        Db::rollback();
                        $this->error("退房失败，联系客服");
                    }


                }else{

                    //小时房 无结束日期 付款时 扣除了最迟到12点的费用 和基础服务费的费用 ，所以要实时计算用户退房需要扣除的费用
                    //和用户入住计费的时间进行换算 由于程序的定时任务 会自动在12点给订单结束，所以理论上，不会超过12点，
                    $overtimeminute = $oinfo['overtimeminute'];
                    $stime_move = $oinfo['moveinto_time'];

                    //当前时间小于入住时间 按照最低一小时扣费
                    if($now <= $stime_move){
                        $hour2 = 1;
                    }else{
                        //总之 无结束日期的小时房 最多不会超过 30个小时 如果就是超过了30小时 也按照 30小时计算
                        $countday = getDatediffedaytemp($stime_move,$now);

                        $hour = 0;
                        if($countday == 1){
                            $hour = 24;
                        }
                        $counthour = getDatediffemintemp($stime_move,$now);


                        $hour2 = floor($counthour/60) + $hour;

                        $min = ($counthour - $hour2*60);
                        if($min >= $overtimeminute){
                            $hour2++;
                        }
                    }


                    //判断是否需要退款 如果超过了一天的费用 则按照封顶价扣费
                    $price = $oinfo['price'];
                    $number = $oinfo['number'];//预定房间数量

                    $allprice = $price * $hour2;//房费
                    if($allprice >= $oinfo['totalprice']){
                        $allprice = $oinfo['totalprice'];
                    }

                    $yfallprice = $oinfo['all_money'] - $oinfo['ballprice'];//已付费用（包括押金和基础服务费 基础服务费不退）
                    $retrunmoney = $yfallprice - $allprice * $number;

                    $orderup['pay_status'] = "3";//订单状态
                    $orderup['all_price'] = $allprice * $number;//实际房费
                    $orderup['refund_status'] = 3;//退款状态 抵消费用 无需退款
                    $orderup['return_money'] = $retrunmoney;// 无需退款 动态计算房费
                    $orderup['income'] = $oinfo['all_money'] - $retrunmoney;//收入等于支付的金额
                    $orderup['checkout_time'] = $now;//退房时间


                    $eff1 = $odb->where(['order_number'=>$ordernumber])->update($orderup);

                    //如果退款大于0 则 写入余额退款日志
                    if($retrunmoney > 0){
                        //余额支付 追加 退款 日志
                        $moneylog['createtime'] = $now;
                        $moneylog['type'] = 1;
                        $moneylog['user_id'] = $oinfo['user_id'];
                        $moneylog['nickname'] = $userinfo['nickName'];
                        $moneylog['memo'] = "余额付款-".$hinfo['hoteltitle'];
                        $moneylog['service_ids'] = $oinfo['order_number'];
                        $moneylog['money'] = $retrunmoney;
                        $moneylog['type2'] = 1;
                        $moneylog['before'] = $userinfo['money'];
                        $moneylog['after'] =  $userinfo['money'] + $retrunmoney;
                        //添加消费日志
                        $eff2 = db("user_money_log")->insert($moneylog);
                    }else{
                        $eff2 = true;
                    }

                    //修改用户余额 user表
                    $userup['money'] = $userinfo['money'] + $retrunmoney;
                    $userup['updatetime'] = $now;
                    $eff3 = db("user")->where(["id"=>$oinfo['user_id']])->update($userup);


                    //回归房源状态
                    $rdata["h_statusText"] = "cleaning";
                    $rdata["updatetime"] = $now;
                    $eff4 = $rdb->where("id={$oinfo['room_id']}")->update($rdata);

                    //修改房间属性的数量 修改label表记录
                    if($labels){
                        $number = $oinfo['number'];
                        $eff5 = $labeldb->execute("UPDATE `fa_label` SET `lcount`=`lcount` + $number,`updtime`= $now WHERE  `id` in ($labels) ");
                    }else{
                        $eff5 = true;
                    }
                    if($eff1 && $eff2 && $eff3 && $eff4 && $eff5){
                        Db::commit();
                        if($userinfo["phone"]){
                            //通知用户您入住的房间已经退房
                            //sendCmsg($userinfo["phone"],$houseinfo['h_title']);
                        }
                        if($hinfo["h_phone"]){
                            //通知酒店 用户已经退房，请准时打扫
                            //sendHOmsg($userinfo["phone"],$userinfo["nickName"]);
                        }
                        $this->success("退房成功");
                    }else{
                        Db::rollback();
                        $this->error("退房失败，联系客服");
                    }

                }

            }else{



                //微信支付
                if($oinfo['pay_type'] == "0"){

                    //全日房 和 小时房（有结束日期） 两者情况一样
                    if($oinfo['timing'] == "0" || $oinfo['timing'] == "1"){
                        //微信支付
                        //全日房 支付时 押金和基础服务费和房费都已经付款
                        //退房时 只要修改订单状态就行 无需退款
                        $orderup['pay_status'] = "3";//订单状态
                        $orderup['refund_status'] = 1;//退款状态 抵消费用 无需退款
                        $orderup['return_money'] = 0;// 无需退款 退款金额为0
                        $orderup['income'] = $oinfo['all_money'];//收入等于支付的金额
                        $orderup['checkout_time'] = $now;//退房时间
                        $eff1 = $odb->where(['order_number'=>$ordernumber])->update($orderup);
                        //回归房源状态
                        $rdata["h_statusText"] = "cleaning";
                        $rdata["updatetime"] = $now;
                        $eff2 = $rdb->where("id={$oinfo['room_id']}")->update($rdata);

                        //修改房间属性的数量 修改label表记录
                        if($labels){
                            $number = $oinfo['number'];
                            $eff3 = $labeldb->execute("UPDATE `fa_label` SET `lcount`=`lcount` + $number,`updtime`= $now WHERE  `id` in ($labels) ");
                        }else{
                            $eff3 = true;
                        }

                        if($eff1 && $eff2 && $eff3){
                            Db::commit();
                            if($userinfo["phone"]){
                                //通知用户您入住的房间已经退房
                                //sendCmsg($userinfo["phone"],$houseinfo['h_title']);
                            }
                            if($hinfo["h_phone"]){
                                //通知酒店 用户已经退房，请准时打扫
                                //sendHOmsg($userinfo["phone"],$userinfo["nickName"]);
                            }
                            $this->success("退房成功");
                        }else{
                            Db::rollback();
                            $this->error("退房失败，联系客服");
                        }

                    }else{

                        //小时房 无结束日期 付款时 扣除了最迟到12点的费用 和基础服务费的费用 ，所以要实时计算用户退房需要扣除的费用
                        //和用户入住计费的时间进行换算 由于程序的定时任务 会自动在12点给订单结束，所以理论上，不会超过12点，
                        $overtimeminute = $oinfo['overtimeminute'];
                        $stime_move = $oinfo['moveinto_time'];
                        if($now <= $stime_move){
                            $hour2 = 1;
                        }else{
                            //总之 无结束日期的小时房 最多不会超过 30个小时 如果就是超过了30小时 也按照 30小时计算
                            $countday = getDatediffedaytemp($stime_move,$now);
                            $hour = 0;
                            if($countday == 1){
                                $hour = 24;
                            }
                            $counthour = getDatediffemintemp($stime_move,$now);
                            $hour2 = floor($counthour/60) + $hour;
                            $min = ($counthour - $hour2*60);
                            if($min >= $overtimeminute){
                                $hour2++;
                            }
                        }


                        //判断是否需要退款 如果超过了一天的费用 则按照封顶价扣费
                        $price = $oinfo['price'];
                        $number = $oinfo['number'];//预定房间数量

                        $allprice = $price * $hour2;//房费
                        if($allprice >= $oinfo['totalprice']){
                            $allprice = $oinfo['totalprice'];
                        }
                        $yfallprice = $oinfo['all_money'] - $oinfo['ballprice'];//已付费用（包括押金和基础服务费 基础服务费不退）
                        $retrunmoney = $yfallprice - $allprice * $number;
                        $orderup['all_price'] = $allprice * $number;//实际房费
                        $orderup['pay_status'] = "3";//订单状态
                        $orderup['return_money'] = $retrunmoney;// 无需退款 动态计算房费
                        $orderup['income'] = $oinfo['all_money'] - $retrunmoney;//收入等于支付的金额
                        //如果退款大于0 则 写入余额退款日志

                        if($retrunmoney > 0){
                            $orderup['refund_status'] = 2;//退款状态 申请退款中  等微信退款完成后 改变状态为 3
                            $refund_number = "refund_".date("YmdHis", time()) . rand(10000000, 99999999);
                            $orderup['refund_number'] = $refund_number;
                            //余额支付 追加 退款 日志
                            $moneylog['createtime'] = $now;
                            $moneylog['type'] = 1;
                            $moneylog['user_id'] = $oinfo['user_id'];
                            $moneylog['nickname'] = $userinfo['nickName'];
                            $moneylog['memo'] = "余额付款-".$hinfo['hoteltitle'];
                            $moneylog['service_ids'] = $oinfo['order_number'];
                            $moneylog['money'] = $retrunmoney;
                            $moneylog['type2'] = 1;
                            $moneylog['before'] = $userinfo['money'];
                            $moneylog['after'] =  $userinfo['money'] + $retrunmoney;
                            //添加消费日志
                            $eff2 = db("user_money_log")->insert($moneylog);
                            //走微信退款流程
                            //通过微信api进行退款流程

                            $nonce_str = WxPay::str_rand();//随机32位字符串
                            $total_fee = $oinfo['all_money'] * 100;//总金额，单位：分
                            //$total_fee= 0.01 * 100;//测试 一分钱
                            $refund_fee = $retrunmoney * 100;//退款金额，单位：分
                            //$refund_fee= 0.01 * 100;//测试 一分钱
                            $parma = array(
                                'appid'=> WxPay::appid,
                                'mch_id'=> WxPay::mch_id,
                                'nonce_str'=> $nonce_str,
                                'out_trade_no'=> $oinfo['order_number'],//小程序自定义订单号，支付时后台生成
                                'out_refund_no'=> $refund_number,
                                'refund_fee'=> $refund_fee,
                                'total_fee'=> $total_fee,
                                'transaction_id' => $oinfo['transaction_id'],//小程序平台订单号，微信平台生成
                            );




                            $KEY = WxPay::key;//小程序支付秘钥


                            $parma['sign'] = $this->getSign($parma, $KEY);



                            $post_xml = $this->arrayToXml($parma);//把参数转化成xml格式

                            //向微信平台api发送退款参数
                            $xmlresult = $this->postXmlSSLCurl($post_xml,'https://api.mch.weixin.qq.com/secapi/pay/refund');


                            $array = $this->xml2array($xmlresult);



                            //两个success表示退款成功，无需使用回调，在此进行逻辑处理即可
                            if ($array['RETURN_CODE'] == 'SUCCESS' && $array['RESULT_CODE'] == 'SUCCESS') {
                                $orderup["refund_status"] = 3;

                            }else{
                                $orderup["refund_status"] = 4;
                                $this->error("退款失败");
                            }


                        }else{
                            $eff2 = true;
                            $orderup['refund_status'] = 3;//退款状态 抵消费用 无需退款
                        }

                        $orderup['checkout_time'] = $now;//退房时间
                        $eff1 = $odb->where(['order_number'=>$ordernumber])->update($orderup);

                        //修改用户余额 user表
                        $userup['money'] = $userinfo['money'] + $retrunmoney;
                        $userup['updatetime'] = $now;
                        $eff3 = db("user")->where(["id"=>$oinfo['user_id']])->update($userup);


                        //回归房源状态
                        $rdata["h_statusText"] = "cleaning";
                        $rdata["updatetime"] = $now;
                        $eff4 = $rdb->where("id={$oinfo['room_id']}")->update($rdata);

                        //修改房间属性的数量 修改label表记录
                        if($labels){
                            $number = $oinfo['number'];
                            $eff5 = $labeldb->execute("UPDATE `fa_label` SET `lcount`=`lcount` + $number,`updtime`= $now WHERE  `id` in ($labels) ");
                        }else{
                            $eff5 = true;
                        }
                        if($eff1 && $eff2 && $eff3 && $eff4 && $eff5){
                            Db::commit();
                            if($userinfo["phone"]){
                                //通知用户您入住的房间已经退房
                                //sendCmsg($userinfo["phone"],$houseinfo['h_title']);
                            }
                            if($hinfo["h_phone"]){
                                //通知酒店 用户已经退房，请准时打扫
                                //sendHOmsg($userinfo["phone"],$userinfo["nickName"]);
                            }
                            if($retrunmoney > 0){
                                $this->success("退房成功,退款成功，请核实");
                            }else{
                                $this->success("退房成功,费用抵扣，无需退款");
                            }



                        }else{
                            Db::rollback();
                            $this->error("退房失败，联系客服");
                        }

                    }

                }else{

                    //小时卡&微信支付 只针对小时房
                    //有结束日期的 小时房 已经 付过了，主要考虑 到底使用的小时卡是否足够
                    //由于支付时就扣掉了小时卡 并且计算出了 做多使用的小时卡数和需要微信支付的费用（基础服务费、部分房费），部分费用被全部记录到日志money2
                    //所以这里退款根据记录的费用去掉 基础服务费后如果还大于押金 则多余的费用就是额外的房费；计算房费：money2 - ballprice - despoit
                    //有结束日期，不需要押金 但基础服务费部分是必须微信付款的，所以也符合，小时卡只能抵扣房费，所以money2 就只是 基础服务费和部分房费，
                    //付款时 就把这些费用计算清楚了（如果小时卡够，直接抵扣，微信只付款基础服务费；如果小时卡不够，那就是基础服务费和部分房费），所以，退房时，无需走微信支付退款。
                    if($oinfo['timing'] == "0"){
                        $this->error("全日房不能小时卡支付");
                    }
                    if($oinfo['timing'] == "1"){

                        //微信支付 小时房 有结束日期
                        //全日房 支付时 押金和基础服务费和房费都已经付款
                        //退房时 只要修改订单状态就行 无需退款
                        $umlog = db("user_money_log")->where(['service_ids'=>$oinfo['order_number']])->find();
                        if($umlog){
                            $hour = (int)$umlog['money'];
                            $wx_income = (float)$umlog['money2'];
                        }else{
                            $hour = 0;
                            $wx_income = 0;
                        }


                        $orderup['use_hour'] = $hour;//实际使用小时卡
                        $orderup['wx_income'] = $wx_income;//实际微信支付

                        $orderup['pay_status'] = "3";//订单状态
                        $orderup['refund_status'] = 1;//退款状态 抵消费用 无需退款
                        $orderup['return_money'] = 0;// 无需退款 退款金额为0
                        $orderup['income'] = $wx_income;// 实际微信的付款（由于小时卡购买时已经付过钱了，这里只是微信部分付款的统计）
                        $orderup['checkout_time'] = $now;//退房时间


                        $eff1 = $odb->where(['order_number'=>$ordernumber])->update($orderup);

                        //回归房源状态
                        $rdata["h_statusText"] = "cleaning";
                        $rdata["updatetime"] = $now;
                        $eff2 = $rdb->where("id={$oinfo['room_id']}")->update($rdata);

                        //修改房间属性的数量 修改label表记录
                        if($labels){
                            $number = $oinfo['number'];
                            $eff3 = $labeldb->execute("UPDATE `fa_label` SET `lcount`=`lcount` + $number,`updtime`= $now WHERE  `id` in ($labels) ");
                        }else{
                            $eff3 = true;
                        }

                        if($eff1 && $eff2 && $eff3){
                            Db::commit();
                            if($userinfo["phone"]){
                                //通知用户您入住的房间已经退房
                                //sendCmsg($userinfo["phone"],$houseinfo['h_title']);
                            }
                            if($hinfo["h_phone"]){
                                //通知酒店 用户已经退房，请准时打扫
                                //sendHOmsg($userinfo["phone"],$userinfo["nickName"]);
                            }
                            $this->success("退房成功");
                        }else{
                            Db::rollback();
                            $this->error("退房失败，联系客服");
                        }

                    }else{

                        //无结束日期的小时房
                        //费用计算逻辑：预收全天的房费（即换算成对应的全天的小时卡数） + 微信费用（押金+基础服务）
                        //退款：根据实际情况 回退小时卡，如果小时卡充足，押金全退，如果不够，从押扣除，押金退回部分；
                        //如果是无结束日期的，会自动到12点，到时没有退房，程序会自动修改订单状态，发送短信，所以计算最迟以12点计算，超过了12点，只要退款押金即可

                        //小时卡数据
                        if($oinfo['cardid']){
                            $carddata = db("user_card")->where(['id'=>$oinfo['cardid']])->find();
                            $lesshour = $carddata["less_hours"];
                        }else{
                            $lesshour = 0;
                        }

                        //支付时写入的数据
                        $moneydata = db("user_money_log")->where(['service_ids'=>$oinfo['order_number']])->find();


                        $overtimeminute = $oinfo['overtimeminute'];
                        //入住计费时间
                        $stime_move = $oinfo['moveinto_time'];

                        //自动计算的离开时间
                        $etime_move = $oinfo['etime'];


                        $moneylog['createtime'] = $now;
                        $moneylog['user_id'] = $oinfo['user_id'];
                        $moneylog['nickname'] = $userinfo['nickName'];
                        $moneylog['memo'] = "小时卡&微信支付-".$hinfo['hoteltitle'];
                        $moneylog['service_ids'] = $oinfo['order_number'];


                        //总之 无结束日期的小时房 最多不会超过 30个小时 如果就是超过了30小时 也按照 30小时计算
                        $countday = getDatediffedaytemp($stime_move,$now);
                        $hour = 0;
                        if($countday == 1){
                            $hour = 24;
                        }

                        $counthour = getDatediffemintemp($stime_move,$now);
                        //实际入住的小时数
                        $hour2 = floor($counthour/60) + $hour;
                        $min = ($counthour - $hour2*60);
                        if($min >= $overtimeminute){
                            $hour2++;
                        }

                        //无结束日期 去最多应扣掉的小时数， 向上取整 后续根据实际情况回退 这里固定扣除一天最多10小时 配置
                        $confighour = db("config")->field("value")->where(['id'=>37])->find();
                        if($confighour && $confighour['value']){
                            $maxhour = $confighour['value'];
                        }else{
                            $maxhour = 10;
                        }

                        //小时数最多不能超过配置的
                        if($hour2 >10){
                            $hour2 = $maxhour;
                        }


                        //日志中的money 大于或者等于 $hour2
                        //$money2 是押金和基础服务费和部分房费
                        if($hour2 > $moneydata['money']){
                            $returnhourflag = false;
                            $returnhour = 0;
                            $retrunmoney = $oinfo['deposit'] - $oinfo['price'] * ($hour2-$moneydata['money']);//从押金中扣除超时的费用
                            if($retrunmoney <=0){
                                $retrunmoney = 0;
                            }
                            //实时小时大于用户已经扣掉的小时数，其余部分需要微信扣款 扣款金额 单价 * ($hour2 - $moneydata['money'])
                            //退款金额  从微信抵扣
                            $moneylog['money'] = $retrunmoney;//小时卡回退0小时
                            $moneylog['money2'] =  $moneydata['money2'] - $oinfo['deposit'] + $oinfo['price'] * ($hour2-$moneydata['money']);//收入等于已付金额 + 超出的小时费用
                            $moneylog['type'] = 0;//微信&小时卡支付 退款到微信里 因为小时卡显示的是小时数，这里需要显示金额 所以放到微信支付下
                            $moneylog['type2'] = 1;
                            $moneylog['before'] = 0;
                            $moneylog['after'] =  0;
                            $eff1 = true;
                            $eff11 = true;
                            //房费
                            $orderup['all_price'] = $oinfo['price'] * $hour2 * $oinfo['number'];//实际房费
                            //收入
                            $orderup['income'] = $moneylog['money2'];//收入等于已付金额 + 超出的小时费用
                            $orderup['use_hour'] = $moneydata['money'];//实际使用小时卡
                            $orderup['wx_income'] = $orderup['income'];//实际微信支付 已付金额 + 超出的小时费用


                        }elseif ($hour2 == $moneydata['money']){
                            $returnhourflag = false;
                            $returnhour = 0;
                            $retrunmoney = $oinfo['deposit'];//返回全部押金
                            if($retrunmoney <=0){
                                $retrunmoney = 0;
                            }
                            //已付小时数刚好抵消 押金全退
                            $moneylog['money'] = $retrunmoney;//小时卡回退0小时
                            $moneylog['money2'] = $moneydata['money2'] - $oinfo['deposit'];
                            $moneylog['type'] = 0;
                            $moneylog['type2'] = 1;
                            $moneylog['before'] = 0;
                            $moneylog['after'] =  0;
                            $eff1 = true;
                            $eff11 = true;
                            //房费
                            $orderup['all_price'] = $oinfo['price'] * $hour2 * $oinfo['number'];//实际房费
                            //收入
                            $orderup['income'] =  $moneylog['money2'] ;//相当于用户所有房费都用小时卡扣款，实际收入就是 基础服务费
                            $orderup['use_hour'] = $moneydata['money'];//实际使用小时卡
                            $orderup['wx_income'] = $orderup['income'];//实际微信支付 已付金额

                        }else{

                            $returnhourflag = true;
                            //已付小时数 大于 实际消费的
                            //回退小时卡信息 和 押金
                            $return_hour = $moneydata['money'] - $hour2;
                            $returnhour = $return_hour;
                            $retrunmoney = $oinfo['deposit'];//已付押金
                            if($retrunmoney <=0){
                                $retrunmoney = 0;
                            }
                            $moneylog['money'] = $return_hour;//小时卡回退0小时
                            $moneylog['money2'] =  $moneydata['money2'] - $oinfo['deposit'];
                            $moneylog['type'] = 2;
                            $moneylog['type2'] = 1;
                            $moneylog['before'] = $carddata['less_hours'];
                            $moneylog['after'] =  $carddata['less_hours'] + $return_hour;

                            $cardup['updatetime'] = $now;
                            $cardup['status'] = 1;
                            $cardup['less_hours'] = $carddata['less_hours'] + $return_hour;
                            $eff1 = db("user_card")->where(['id'=>$carddata['id']])->update($cardup);

                            //房费
                            $orderup['all_price'] = $oinfo['price'] * $hour2 * $oinfo['number'];//实际房费
                            //收入
                            $orderup['income'] =  $moneylog['money2'];// 相当于用户所有房费都用小时卡扣款，实际收入就是 基础服务费

                            $orderup['use_hour'] = $hour2;//实际使用小时卡
                            $orderup['wx_income'] = $orderup['income'];//实际微信支付 只是基础服务费


                            //追加微信退款记录
                            $moneylog22['createtime'] = $now;
                            $moneylog22['user_id'] = $oinfo['user_id'];
                            $moneylog22['nickname'] = $userinfo['nickName'];
                            $moneylog22['memo'] = "小时卡&微信支付-".$hinfo['hoteltitle'];
                            $moneylog22['service_ids'] = $oinfo['order_number'];
                            $moneylog22['money'] = $retrunmoney;//微信退款
                            $moneylog22['remark'] = "小时卡退回：".$return_hour."小时，微信退回：".$retrunmoney."元";
                            $moneylog22['money2'] =  $return_hour;
                            $moneylog22['type'] = 0;
                            $moneylog22['type2'] = 1;
                            $moneylog22['before'] = $carddata['less_hours'];
                            $moneylog22['after'] =  $carddata['less_hours'] + $return_hour;
                            $eff11 = db("user_money_log")->insert($moneylog);

                        }



                        //添加消费日志
                        $eff2 = db("user_money_log")->insert($moneylog);
                        $orderup['pay_status'] = "3";//订单状态
                        $orderup['return_money'] = $retrunmoney;// 退款金额

                        if($retrunmoney > 0){

                            //走微信退款
                            $orderup['refund_status'] = 2;//退款状态 申请退款中  等微信退款完成后 改变状态为 3
                            $refund_number = "refund_".date("YmdHis", time()) . rand(10000000, 99999999);
                            $orderup['refund_number'] = $refund_number;

                            //走微信退款流程
                            //通过微信api进行退款流程

                            $nonce_str = WxPay::str_rand();//随机32位字符串
                            $total_fee = $oinfo['all_money'] * 100;//总金额，单位：分
                            //$total_fee= 0.01 * 100;//测试 一分钱
                            $refund_fee = $retrunmoney * 100;//退款金额，单位：分
                            //$refund_fee= 0.01 * 100;//测试 一分钱
                            $parma = array(
                                'appid'=> WxPay::appid,
                                'mch_id'=> WxPay::mch_id,
                                'nonce_str'=> $nonce_str,
                                'out_trade_no'=> $oinfo['order_number'],//小程序自定义订单号，支付时后台生成
                                'out_refund_no'=> $refund_number,
                                'refund_fee'=> $refund_fee,
                                'total_fee'=> $total_fee,
                                'transaction_id' => $oinfo['transaction_id'],//小程序平台订单号，微信平台生成
                            );

                            $KEY = WxPay::key;//小程序支付秘钥
                            $parma['sign'] = $this->getSign($parma, $KEY);
                            $post_xml = $this->arrayToXml($parma);//把参数转化成xml格式
                            //向微信平台api发送退款参数
                            $xmlresult = $this->postXmlSSLCurl($post_xml,'https://api.mch.weixin.qq.com/secapi/pay/refund');
                            $array = $this->xml2array($xmlresult);
                            //两个success表示退款成功，无需使用回调，在此进行逻辑处理即可
                            if ($array['RETURN_CODE'] == 'SUCCESS' && $array['RESULT_CODE'] == 'SUCCESS') {
                                $orderup["refund_status"] = 3;

                            }else{
                                $orderup["refund_status"] = 4;
                                $this->error("退款失败");
                            }
                            $orderup['checkout_time'] = $now;//退房时间
                            $eff3 = $odb->where(['order_number'=>$ordernumber])->update($orderup);

                            if($returnhourflag){
                                //修改用户小时卡 user表
                                $userup['hours'] = $userinfo['hours'] + $returnhour;
                                $userup['updatetime'] = $now;
                                $eff4 = db("user")->where(["id"=>$oinfo['user_id']])->update($userup);
                            }else{
                                $eff4 = true;
                            }

                            //回归房源状态
                            $rdata["h_statusText"] = "cleaning";
                            $rdata["updatetime"] = $now;
                            $eff5 = $rdb->where("id={$oinfo['room_id']}")->update($rdata);

                            //修改房间属性的数量 修改label表记录
                            if($labels){
                                $number = $oinfo['number'];
                                $eff6 = $labeldb->execute("UPDATE `fa_label` SET `lcount`=`lcount` + $number,`updtime`= $now WHERE  `id` in ($labels) ");
                            }else{
                                $eff6 = true;
                            }
                            if($eff1 && $eff2 && $eff3 && $eff4 && $eff5 && $eff6 && $eff11){
                                Db::commit();
                                if($userinfo["phone"]){
                                    //通知用户您入住的房间已经退房
                                    //sendCmsg($userinfo["phone"],$houseinfo['h_title']);
                                }
                                if($hinfo["h_phone"]){
                                    //通知酒店 用户已经退房，请准时打扫
                                    //sendHOmsg($userinfo["phone"],$userinfo["nickName"]);
                                }

                                $this->success("退房成功,退款成功，请核实");


                            }else{
                                Db::rollback();
                                $this->error("退房失败，联系客服");
                            }

                        }else{
                            //不走微信
                            $orderup['refund_status'] = 3;//自动完成
                            $orderup['checkout_time'] = $now;//退房时间

                            $eff3 = $odb->where(['order_number'=>$ordernumber])->update($orderup);

                            if($returnhourflag){
                                //修改用户小时卡 user表
                                $userup['hours'] = $userinfo['hours'] + $returnhour;
                                $userup['updatetime'] = $now;
                                $eff4 = db("user")->where(["id"=>$oinfo['user_id']])->update($userup);
                            }else{
                                $eff4 = true;
                            }

                            //回归房源状态
                            $rdata["h_statusText"] = "cleaning";
                            $rdata["updatetime"] = $now;
                            $eff5 = $rdb->where("id={$oinfo['room_id']}")->update($rdata);

                            //修改房间属性的数量 修改label表记录
                            if($labels){
                                $number = $oinfo['number'];
                                $eff6 = $labeldb->execute("UPDATE `fa_label` SET `lcount`=`lcount` + $number,`updtime`= $now WHERE  `id` in ($labels) ");
                            }else{
                                $eff6 = true;
                            }
                            if($eff1 && $eff2 && $eff3 && $eff4 && $eff5 && $eff6 && $eff11){
                                Db::commit();
                                if($userinfo["phone"]){
                                    //通知用户您入住的房间已经退房
                                    //sendCmsg($userinfo["phone"],$houseinfo['h_title']);
                                }
                                if($hinfo["h_phone"]){
                                    //通知酒店 用户已经退房，请准时打扫
                                    //sendHOmsg($userinfo["phone"],$userinfo["nickName"]);
                                }
                                $this->success("退房成功,费用抵扣，无需退款");


                            }else{
                                Db::rollback();
                                $this->error("退房失败，联系客服");
                            }

                        }

                    }

                }


            }

        }else{
            $this->error("订单数据错误");
        }

    }

    //我的账单 0 微信支付 1 余额支付 2 小时卡（微信支付） 3套餐消费 9 全部
    public function myBill(){
        $uid = $this->request->request("uid");
        $type = $this->request->request("type",9);
        $month = $this->request->request("month");
        $page = $this->request->request("page",1);
        $limit = $this->request->request("limit",6);
        if(empty($uid)){
            $this->error("参数错误");
        }

        $marr = getthemonth($month);
        $startdate = strtotime($marr[0]);
        $enddate = strtotime($marr[1]." 23:59:59");


        if($type == 9){
            $count =  db("user_money_log")
                ->where(['user_id'=>$uid])
                ->where("createtime >= $startdate && createtime <= $enddate")
                ->count();
            $list = db("user_money_log")
                ->where(['user_id'=>$uid])
                ->where("createtime >= $startdate && createtime <= $enddate")
                ->page($page,$limit)
                ->order("id desc")
                ->select();
        }else{
            $count =  db("user_money_log")
                ->where(['user_id'=>$uid])
                ->where("`type` = {$type}")
                ->where("createtime >= $startdate && createtime <= $enddate")
                ->count();

            $list = db("user_money_log")
                ->where(['user_id'=>$uid])
                ->where("type = {$type}")
                ->where("createtime >= $startdate && createtime <= $enddate")
                ->page($page,$limit)
                ->order("id desc")
                ->select();
        }

        //type2 0支出 1退回 2充值 3购买 4赠送
        if($list){
            foreach ($list as &$v){
                $v['memo'] = subText3($v['memo'],15);
                if($v['type2'] == 1){
                    $v['typeText'] = "退回";
                    $v['typecolor'] = 1;

                    if($v['type'] == 2){
                        $v['money'] = "+".$v['money']."小时";
                    }else{
                        $v['money'] = "+".$v['money'];
                    }
                }elseif ($v['type2'] == 2){
                    $v['typeText'] = "充值";
                    $v['typecolor'] = 1;

                    if($v['type'] == 2){
                        $v['money'] = "-".$v['money']."小时";
                    }else{
                        $v['money'] = "+".$v['money'];
                    }
                }elseif ($v['type2'] == 4){
                    $v['typeText'] = "赠送";
                    $v['typecolor'] = 1;

                    if($v['type'] == 2){
                        $v['money'] = "+".$v['money']."小时";
                    }else{
                        $v['money'] = "+".$v['money'];
                    }
                }elseif ($v['type2'] == 3){
                    $v['typeText'] = "购买";
                    $v['typecolor'] = 1;

                    if($v['type'] == 2){
                        $v['money'] = "+".sprintf("%1\$.0f",$v["money"])."小时";
                    }else{
                        $v['money'] = "+".$v['money'];
                    }
                }else{
                    $v['typeText'] = "支出";
                    $v['typecolor'] = 0;
                    if($v['type'] == 2){
                        $v['money'] = "-".$v['money']."小时";
                    }else{
                        $v['money'] = "-".$v['money'];
                    }
                }



                $v['createtime'] = date("m月d日 H:i:s",$v['createtime']);

                unset($v['type2']);
                unset($v['user_id']);
                unset($v['before']);
                unset($v['after']);
                unset($v['service_ids']);
            }

            //分页数据
            $res['rowCount'] = $count;
            $res['pageCount'] = ceil($count/$limit);
            $res['pageSize'] = $limit;
            $res['pageIndex'] = $page;
            $res['rowData'] = $list;

            $this->success("success",$res);

        }else{
            $this->success("暂无记录",[]);
        }

    }

    //收藏 点击收藏 如果存在则是取消，不存在则是新增
    public function collect(){
        $uid = $this->request->request("uid");
        $hid = $this->request->request("hid");

        if(empty($hid) || empty($uid)){
            $this->error("参数错误");
        }
        $cl = db("collect");
        $has = $cl->where(['uid'=>$uid,'hid'=>$hid])->find();
        if($has){
            $del = $cl->delete($has['id']);
            if($del){
                $this->success("取消成功");
            }else{
                $this->error("取消失败");
            }
        }else{
            $data['uid'] = $uid;
            $data['hid'] = $hid;
            $data['addtime'] = date("Y-m-d H:I:S",time());
            if($cl->insertGetId($data)){
                $this->success("收藏成功");
            }else{
                $this->error("收藏失败");
            }
        }





    }

    //我的收藏
    public function myCollect(){
        $cldb = db("collect");
        $tps = db("type");
        $htps = db("htype");
        $rdb = db("house");
        $w=date('w');

        $lng1 = $this->request->request("lng");
        $lat1 = $this->request->request("lat");
        $uid = $this->request->request("uid");
        $ftype = $this->request->request("type");
        //开始结束时间 用来 筛选单价
        $stime = $this->request->request("stime");
        $etime = $this->request->request("etime");

        if($stime){
            $stime0 = strtotime(date("Y-m-d",strtotime($stime)));
            $stime24 = strtotime(date("Y-m-d 23:59:59",strtotime($stime)));
        }
        $etime = $this->request->request("etime");

        if($etime){
            $etime0 = strtotime(date("Y-m-d",strtotime($etime)));
            $etime24 = strtotime(date("Y-m-d 23:59:59",strtotime($etime)));
        }

        //新增关房判断 筛选出酒店下不能预定的房间id 排除这些 随机选择一个 即可
        $closearr[] =[];
        $closestr = "";
        //关闭的房间数据
        $closelist = db("closeroom")
            ->where("cstime >= '$stime0' && cetime2 <= '$etime24' || cetime2 >='$stime0' && cstime <= '$stime0' || cetime2 >= $stime0 && cstime <= $etime24")
            ->field("crid")
            ->select();


        if($closelist){
            foreach ($closelist as $v){
                $closearr[] = $v['crid'];
                $closestr .=  $v['crid'].",";
            }
        }

        if($closestr){
            $closestr = rtrim($closestr,",");
        }



        $page = $this->request->request("page",1);
        //$limit = $this->request->request("limit",6);
        $limit = 100000;

        if(empty($uid)){
            $this->error('uid参数错误');
        }

        if(empty($lng1) || empty($lat1)){
            $this->error('经纬度参数错误');
        }


        $count = $cldb
            ->where(['uid'=>$uid])
            ->count();

        $list = $cldb
            ->where(['uid'=>$uid])
            ->join('hotels hl','hl.hid=fa_collect.hid')
            ->field("hl.hid,hl.hoteltitle as title,hl.h_img as img,hl.lng,hl.lat,hl.h_lebals as labels,hl.h_htypes as htypes,hl.h_types as types,hl.h_point as point")
            ->page($page,$limit)
            ->select();



        //平分等级 目前只考虑整数 评论分 1一般 2 普通 3 很好 4 推荐 5 超棒
        $pointer = [
            "1"=>'一般',
            "2"=>'普通',
            "3"=>'很好',
            "4"=>'推荐',
            "5"=>'超棒',
        ];

        if($list){
            $templist = [];
            foreach ($list as $k=>&$v){
                $types = [];
                $typearr = [];
                $nowpont = $v['point'];
                if($nowpont<1){
                    $nowpont = 1;
                }
                if($nowpont>51){
                    $nowpont = 5;
                }
                $v['pointname'] = $pointer[$nowpont];
                $v['img'] = $this->mainhost.$v['img'];
                //房属性
                $type = $v["types"];
                if($type){
                    $typearr = $tps->where("id in ($type)")->field("ttitle")->select();
                }

                if($typearr){
                    foreach ($typearr as $vv){
                        $types[] = $vv["ttitle"] ;
                    }
                }
                //房型
                $labels = [];
                $labelarr = [];
                $label = $v["htypes"];
                if($label){
                    $labelarr = $htps->where("id in ($label)")->field("ttitle")->select();
                }

                if($labelarr){
                    foreach ($labelarr as $vv){
                        $labels[] = $vv["ttitle"] ;
                    }
                }
                $v['types'] = $types;
                $v['htypes'] = $labels;

                //多少分钟前有人预定 ，这里随机一个数字
                $v['min'] = mt_rand(10,40)."分钟前有人预定";

                //取出房间价格最小的一个房间的信息


                if($closestr){
                    $info = $rdb
                        ->where(['h_id'=>$v['hid'],'h_status'=>'normal','h_statusText'=>'normal'])
                        ->where("id not in ($closestr)")
                        ->field("id,h_id,h_price,h_weekprice,h_allprice")
                        ->order("h_price asc")
                        ->find();
                }else{
                    $info = $rdb
                        ->where(['h_id'=>$v['hid'],'h_status'=>'normal','h_statusText'=>'normal'])
                        ->field("id,h_id,h_price,h_weekprice,h_allprice")
                        ->order("h_price asc")
                        ->find();
                }

                if($info){
                    $v['rid'] = $info['id'];//房间id
                    //判断是否有日历价格 如果用户选择开始时间 要以 用户选择的时间段为准 考虑是否在活动或者周末价范围
                    $dateStr = date('Y-m-d 00:00:00', time());

                    if($ftype == 1){
                        $v['unit'] = "元/时";
                        $timestamp0 = strtotime($dateStr);
                        $where2["starttime"] = $timestamp0;
                        $where2["f_id"] = $info["id"];
                        $rdata = db("calendar")->where($where2)->find();
                        if($rdata){
                            $v['price'] = sprintf("%1\$.2f",$rdata["title"]);
                        }else{
                            //判断是否取周末价
                            if($w == 5 || $w == 6){
                                if($info["h_weekprice"] != 0){
                                    $v['price'] = sprintf("%1\$.2f",$info["h_weekprice"]);
                                }else{
                                    $v['price'] = $info['h_price'];
                                }
                            }else{
                                $v['price'] = $info['h_price'];
                            }
                        }


                    }else{
                        $v['unit'] = "元/天";
                        $v['price'] = $info['h_allprice'];
                    }

                }else{
                    continue;
                }

                //备注文字
                $v['tip'] = "随时可住，2小时起租";

                //距离
                $v["distance"] = "距离定位位置".getdistancekm($lng1,$lat1,$v["lng"],$v["lat"])."km";
                $sort[] = $v["distance"];
                $templist[$k] = $v;

            }

            array_multisort($sort,SORT_DESC,$templist);
            $offset = ($page-1)*$limit;
            $templist = array_slice($templist,$offset,$limit);


            //分页数据
            $res['rowCount'] = $count;
            $res['pageCount'] = ceil($count/$limit);
            $res['pageSize'] = $limit;
            $res['pageIndex'] = $page;
            $res['rowData'] = $templist;

            $this->success("success",$res);
        }else{
            $this->error("暂无数据");
        }


    }

    //入住过
    public function myUsed(){
        $cldb = db("order");
        $tps = db("type");
        $htps = db("htype");
        $rdb = db("house");
        $w=date('w');

        $lng1 = $this->request->request("lng");
        $lat1 = $this->request->request("lat");
        $uid = $this->request->request("uid");
        $ftype = $this->request->request("type");
        $stime = $this->request->request("stime");
        $etime = $this->request->request("etime");

        if($stime){
            $stime0 = strtotime(date("Y-m-d",strtotime($stime)));
            $stime24 = strtotime(date("Y-m-d 23:59:59",strtotime($stime)));
        }
        $etime = $this->request->request("etime");

        if($etime){
            $etime0 = strtotime(date("Y-m-d",strtotime($etime)));
            $etime24 = strtotime(date("Y-m-d 23:59:59",strtotime($etime)));
        }

        //开始结束时间 用来 筛选单价
        $page = $this->request->request("page",1);
        //$limit = $this->request->request("limit",6);
        $limit = 10000;



        //新增关房判断 筛选出酒店下不能预定的房间id 排除这些 随机选择一个 即可
        $closearr[] =[];
        $closestr = "";
        //关闭的房间数据
        $closelist = db("closeroom")
            ->where("cstime >= '$stime0' && cetime2 <= '$etime24' || cetime2 >='$stime0' && cstime <= '$stime0' || cetime2 >= $stime0 && cstime <= $etime24")
            ->field("crid")
            ->select();


        if($closelist){
            foreach ($closelist as $v){
                $closearr[] = $v['crid'];
                $closestr .=  $v['crid'].",";
            }
        }

        if($closestr){
            $closestr = rtrim($closestr,",");
        }



        if(empty($uid)){
            $this->error('uid参数错误');
        }

        if(empty($lng1) || empty($lat1)){
            $this->error('经纬度参数错误');
        }


        $count = $cldb
            ->where(['user_id'=>$uid,'pay_status'=>"3"])
            ->count();

        //倒叙 不以距离排序
        $list = $cldb
            ->where(['user_id'=>$uid,'pay_status'=>"3"])
            ->join('hotels hl','hl.hid=fa_order.hotelid')
            ->field("fa_order.stime as time,hl.hid,hl.hoteltitle as title,hl.h_img as img,hl.lng,hl.lat,hl.h_lebals as labels,hl.h_htypes as htypes,hl.h_types as types,hl.h_point as point")
            ->order("id desc")
            ->page($page,$limit)
            ->select();



        //平分等级 目前只考虑整数 评论分 1一般 2 普通 3 很好 4 推荐 5 超棒
        $pointer = [
            "1"=>'一般',
            "2"=>'普通',
            "3"=>'很好',
            "4"=>'推荐',
            "5"=>'超棒',
        ];

        if($list){
            $templist = [];
            foreach ($list as $k=>&$v){
                $v['time'] = date("Y年m月d日",$v['time']);
                $types = [];
                $typearr = [];

                $nowpont = $v['point'];
                if($nowpont<1){
                    $nowpont = 1;
                }
                if($nowpont>51){
                    $nowpont = 5;
                }

                $v['pointname'] = $pointer[$nowpont];
                $v['img'] = $this->mainhost.$v['img'];
                //房属性
                $type = $v["types"];
                if($type){
                    $typearr = $tps->where("id in ($type)")->field("ttitle")->select();
                }

                if($typearr){
                    foreach ($typearr as $vv){
                        $types[] = $vv["ttitle"] ;
                    }
                }
                //房型
                $labels = [];
                $labelarr = [];
                $label = $v["htypes"];
                if($label){
                    $labelarr = $htps->where("id in ($label)")->field("ttitle")->select();
                }

                if($labelarr){
                    foreach ($labelarr as $vv){
                        $labels[] = $vv["ttitle"] ;
                    }
                }
                $v['types'] = $types;
                $v['htypes'] = $labels;

                //多少分钟前有人预定 ，这里随机一个数字
                $v['min'] = mt_rand(10,40)."分钟前有人预定";

                //取出房间价格最小的一个房间的信息  这里暂时不考虑时间，如果 找不到酒店 ，就不显示
                if($closestr){
                    $info = $rdb->where(['h_id'=>$v['hid'],'h_status'=>'normal','h_statusText'=>'normal'])->where("id not in ($closestr)")->field("id,h_id,h_price,h_weekprice,h_allprice")->order("h_price asc")->find();
                }else{
                    $info = $rdb->where(['h_id'=>$v['hid'],'h_status'=>'normal','h_statusText'=>'normal'])->field("id,h_id,h_price,h_weekprice,h_allprice")->order("h_price asc")->find();
                }

                if($info){
                    $v['rid'] = $info['id'];//房间id
                    //判断是否有日历价格 如果用户选择开始时间 要以 用户选择的时间段为准 考虑是否在活动或者周末价范围
                    $dateStr = date('Y-m-d 00:00:00', time());

                    if($ftype == 1){
                        $v['unit'] = "元/时";
                        $timestamp0 = strtotime($dateStr);
                        $where2["starttime"] = $timestamp0;
                        $where2["f_id"] = $info["id"];
                        $rdata = db("calendar")->where($where2)->find();
                        if($rdata){
                            $v['price'] = sprintf("%1\$.2f",$rdata["title"]);
                        }else{
                            //判断是否取周末价
                            if($w == 5 || $w == 6){
                                if($info["h_weekprice"] != 0){
                                    $v['price'] = sprintf("%1\$.2f",$info["h_weekprice"]);
                                }else{
                                    $v['price'] = $info['h_price'];
                                }
                            }else{
                                $v['price'] = $info['h_price'];
                            }
                        }


                    }else{
                        $v['unit'] = "元/天";
                        $v['price'] = $info['h_allprice'];
                    }



                }else{
                    continue;
                }

                //备注文字
                $v['tip'] = "随时可住，2小时起租";

                //距离
                $v["distance"] = "距离定位位置".getdistancekm($lng1,$lat1,$v["lng"],$v["lat"])."km";
                $sort[] = $v["distance"];
                $templist[$k] = $v;

            }


            //分页数据
            $res['rowCount'] = $count;
            $res['pageCount'] = ceil($count/$limit);
            $res['pageSize'] = $limit;
            $res['pageIndex'] = $page;
            $res['rowData'] = $list;

            $this->success("success",$res);
        }else{
            $this->error("暂无数据");
        }


    }

    //超时提醒
    //提示：在退房 还有10分钟提醒用户 退房到期 如果用户没有处理 每次进入首页都提醒
    public function myWarning(){
        $uid = $this->request->request("uid");
        if(empty($uid)){
            return;
        }
        $now = time() + 600;
        $oinfo =  db("order")
            ->where(["user_id"=>$uid,'pay_status'=>"2"])
            ->where("etime <= $now")
            ->field("id,order_number")->find();

        if($oinfo){
            $this->success("success",$oinfo,99);
        }else{
            $this->success("暂无提醒");
        }

    }

    //用户信息
    public function getUserinfo(){
        $uid = $this->request->request("uid");
        if(empty($uid)){
            $this->error("用户参数错误");
        }
        $uinfo = db("user")->field("id,nickName,phone,openid,avatarUrl,idcard,birthday,hours,money,ftype")->where(['id'=>$uid])->find();

        if($uinfo){
            //返点比例
            $res2 = model('Config')->where("name='point'")->field("value")->find();
            $point = "0";
            if($res2){
                $point = $res2->toarray()["value"] * 100 ."%";
            }

            //获取用户收藏数量
            $uinfo['collect'] = db("collect")->where(['uid'=>$uid])->count();
            $uinfo['point'] = $point;

            $this->success("success",$uinfo);
        }else{
            $this->error("用户信息有误");
        }

    }

    //修改头像
    public function upAvatar(){

        $file = $this->request->file('file');

        if ($file) {
            $info = $file->move('weixin/');

            if ($info) {
                $file = $info->getSaveName();
                $file = "https://www.yunzhuke.net/weixin/".$file;
                $this->success("头像上传成功",$file);
            }
        }

    }

    //修改用户信息
    public function upUinfo(){
        $uid = $this->request->request("uid");
        $avatarUrl = $data['avatarUrl'] = $this->request->request("avatarUrl");
        $nickName = $data['nickName'] = $this->request->request("nickName");
        $phone = $data['phone'] = $this->request->request("phone");
        $data['idcard'] = $this->request->request("idcard");
        $data['birthday'] = $this->request->request("birthday");
        $data['ftype'] = $this->request->request("ftype",0); //0全部房源 1 小时卡房源

        if(empty($uid)){
            $this->error("用户uid不能为空");
        }
        if(empty($avatarUrl)){
            $this->error("头像必须上传");
        }
        if(empty($nickName)){
            $this->error("姓名不能为空");
        }
        if(empty($phone)){
            $this->error("手机号不能为空");
        }

        $data['updatetime'] = time();
        $eff = db("user")->where(['id'=>$uid])->update($data);

        if($eff){
            $this->success("保存成功");
        }else{
            $this->error("保存失败");
        }


    }

    //上传单图
    public function upOneImg(){

        $file = $this->request->file('file');

        if ($file) {
            $info = $file->move('comments/');

            if ($info) {
                $file = $info->getSaveName();
                $file = "/comments/".$file;
                //$file = "https://www.yunzhuke.net/weixin/".$file;
                $this->success("上传成功",$file);
            }
        }

    }

    //上传多图
    public function upMoreImg(){
        // $files = $this->request->file();
        $ordernumber = $this->request->request("orderNumber");
        $uid = $this->request->request("uid");
        if (empty($ordernumber)){
            $this->error("订单编号不能为空");
        }
        if (empty($uid)){
            $this->error("uid不能为空");
        }
        $file = $_FILES;
        if (empty($file)){
            $this->error("请选择图片");
        }

        $len = count($file['files']['name']);
        $data = [];
        if($len > 0){
            for($i=0;$i<$len;$i++){
                $name = $file['files']['name'][$i];
                $upload_path = "comments".DS; //上传文件的存放路径
                $type = strtolower(substr($name, strrpos($name, '.') + 1));
                $file_name = date('Ymd').time().rand(100,999).'.'.$type;
                if (move_uploaded_file($file['files']['tmp_name'][$i], $upload_path . $file_name)) {
                    $data[] = DS . $upload_path . $file_name;
                    $data2[] = $this->mainhost . DS .$upload_path . $file_name;
                }
            }
        }

        //添加数据库
        if($data){
            $imgstr = implode(",",$data);
        }


        $idata['uid'] = $uid;
        $idata['ordernum'] = $ordernumber;
        $idata['image'] = $imgstr;
        $idata['ctime'] = time();
        $inid = db("comments_img")->insertGetId($idata);

        if($inid){
            $res['id'] = $inid;
            $res['imgs'] = $data2;
            $this->success("图片上传成功",$res);
        }else{
            $this->error("图片上传失败");
        }

    }

    //全部评价 列表 //评论的是房间 但会给酒店综合分
    public function myCommentsList(){
        $uid = $this->request->request("uid");
        $roomid = $this->request->request("roomId");
        if (empty($uid)){
            $this->error("uid不能为空");
        }
        $comment = $this->request->request("comment",1);
        $page = $this->request->request("page",1);
        $limit = $this->request->request("limit",6);


        if($roomid && $comment == 1){
            $list = db("comments")
                ->where(['userdel'=>0,'roomid'=>$roomid])
                ->field("id,uid,memo,images,ctime,goods")
                ->order("id desc")
                ->select();


            if($list){
                foreach ($list as &$v) {

                    $v['ctime'] = date("Y-m-d H:i", $v['ctime']) . " 评价";
                    if ($v['images']) {
                        $imgs = array();
                        $imgarr = explode(",", $v["images"]);
                        $len = count($imgarr);
                        if ($len > 1) {
                            for ($i = 0; $i < $len; $i++) {
                                $imgs[$i] = $this->mainhost . $imgarr[$i];
                            }
                        } else {
                            $imgs[0] = $this->mainhost . $v["images"];
                        }
                        unset($v['images']);
                        $v["imglist"] = $imgs;
                    }
                    $userinfo =  db("user")->where(['id'=>$v['uid']])->field("avatarUrl,nickname")->find();
                    $v["nickname"] = $userinfo['nickname'];
                    $v["avatarUrl"] = $userinfo['avatarUrl'];
                    $v["goods"] = sprintf("%1\$.1f",$v["goods"]);

                }

                //分页数据
                $count = count($list);
                $res['rowCount'] = $count;
                $res['pageCount'] = ceil($count/$limit);
                $res['pageSize'] = $limit;
                $res['pageIndex'] = $page;
                $res['rowData'] = $list;

                $this->success("success",$res);
            }else{
                $this->success("暂无记录",[]);
            }


        }

        if($comment == 0){

            $where = " comment = 0";
            $count = db("order")
                ->where(['user_id'=>$uid,'userdel'=>0])
                ->where($where)
                ->count();


            $list = db("order")
                ->where(['user_id'=>$uid,'userdel'=>0,'pay_status'=>'3'])
                ->where($where)
                ->field("id,room_id as rid,order_number,price,totalprice,room_html,hotelid,all_money,number,moveinto_time,comment,timing")
                ->page($page,$limit)
                ->order("id desc")
                ->select();


            if($list){
                foreach ($list as &$v){
                    $hinfo = db("hotels")->field("hoteltitle,h_address")->where(['hid'=>$v['hotelid']])->find();
                    $roominfo= json_decode($v["room_html"],true);
                    $v['img'] = $this->mainhost.$roominfo['h_img'];
                    $v['stime'] = date("Y-m-d H:i",$v['moveinto_time']);
                    unset($v['moveinto_time']);
                    if($v['timing'] == "0"){
                        $v['price'] = $v['price']."元";
                    }else{
                        $v['price'] = $v['totalprice']."元";
                    }
                    unset($v['totalprice']);
                    $v['title'] = $roominfo['h_title'];
                    $v['htitle'] = $hinfo['hoteltitle'];
                    $v['haddress'] = $hinfo['h_address'];
                    //获取评论数据
                    if($v['comment'] == 1){
                        $comdata = db("comments")->where(['ordernum'=>$v['order_number'],'userdel'=>'0'])->find();
                        if($comdata){
                            $comdata['ctime'] = date("Y.m.d",$comdata['ctime']);
                            $v['cdata'] = $comdata;
                        }else{
                            $v['cdata'] = [];
                        }

                    }else{
                        $v['cdata'] = [];
                    }
                    unset($v['room_html']);
                }

                //分页数据
                $res['rowCount'] = $count;
                $res['pageCount'] = ceil($count/$limit);
                $res['pageSize'] = $limit;
                $res['pageIndex'] = $page;
                $res['rowData'] = $list;

                $this->success("success",$res);
            }else{
                $this->success("暂无记录",[]);
            }
        }


    }


    //全部评价 列表 //评论的是房间 但会给酒店综合分
    public function myCommentsListold(){
        $uid = $this->request->request("uid");
        if (empty($uid)){
            $this->error("uid不能为空");
        }
        $comment = $this->request->request("comment",1);
        $page = $this->request->request("page",1);
        $limit = $this->request->request("limit",6);


        if($comment == 1){
            $where = " comment = 1";
        }else{
            $where = " comment = 0";
        }

        $count = db("order")
            ->where(['user_id'=>$uid,'userdel'=>0])
            ->where($where)
            ->count();

        $list = db("order")
            ->where(['user_id'=>$uid,'userdel'=>0])
            ->where($where)
            ->field("id,room_id as rid,order_number,price,totalprice,room_html,hotelid,all_money,number,moveinto_time,comment,timing")
            ->page($page,$limit)
            ->order("id desc")
            ->select();

        if($list){
            foreach ($list as &$v){


                $hinfo = db("hotels")->field("hoteltitle,h_address")->where(['hid'=>$v['hotelid']])->find();
                $roominfo= json_decode($v["room_html"],true);
                $v['img'] = $this->mainhost.$roominfo['h_img'];
                $v['stime'] = date("Y-m-d H:i",$v['moveinto_time']);
                unset($v['moveinto_time']);
                if($v['timing'] == "0"){
                    $v['price'] = $v['price']."元";
                }else{
                    $v['price'] = $v['totalprice']."元";
                }
                unset($v['totalprice']);
                $v['title'] = $roominfo['h_title'];
                $v['htitle'] = $hinfo['hoteltitle'];
                $v['haddress'] = $hinfo['h_address'];
                //获取评论数据
                if($v['comment'] == 1){
                    $comdata = db("comments")->where(['ordernum'=>$v['order_number'],'userdel'=>'0'])->find();
                    if($comdata){
                        $comdata['ctime'] = date("Y.m.d",$comdata['ctime']);
                        $v['cdata'] = $comdata;
                    }else{
                        $v['cdata'] = [];
                    }

                }else{
                    $v['cdata'] = [];
                }
                unset($v['room_html']);
            }

            //分页数据
            $res['rowCount'] = $count;
            $res['pageCount'] = ceil($count/$limit);
            $res['pageSize'] = $limit;
            $res['pageIndex'] = $page;
            $res['rowData'] = $list;

            $this->success("success",$res);
        }else{
            $this->success("暂无记录",[]);
        }
    }


    //获取评价酒店、房间时间
    public function comRinfo(){
        $ordernumber = $this->request->request("orderNumber");
        if(empty($ordernumber)){
            $this->error("参数有误");
        }
        $info = db("order")->where(['order_number'=>$ordernumber])->field("id,room_html,hotelname")->find();
        if($info){
            $rinfo  = json_decode($info['room_html'],true);

            $res['title'] = $rinfo['h_title'];
            $res['img'] = $this->mainhost.$rinfo['h_img'];
            $res['htitle'] = $info['hotelname'];
            $this->success("success",$res);

        }else{
            $this->error("信息有误");
        }


    }

    //去评价 //更新酒店评分
    public function addComment(){
        $uid = $this->request->request("uid");
        if (empty($uid)){
            $this->error("uid不能为空");
        }
        $rid = $this->request->request("rid");
        if (empty($rid)){
            $this->error("rid不能为空");
        }
        $order_number = $this->request->request("orderNumber");
        if (empty($order_number)){
            $this->error("订单编号不能为空");
        }

        $memo = $this->request->request("memo");
        $goods = $this->request->request("goods");
        $images = $this->request->request("images","");
        $data['images'] = $images;
        if (empty($goods)){
            $this->error("请对满意度打分");
        }
        $data['goods'] = $goods;

        //准备数据
        //被子干净
        $data['weisheng'] = $this->request->request("weisheng",0);
        //空调好用
        $data['huanjing'] = $this->request->request("huanjing",0);
        //服务态度好
        $data['fuwu'] = $this->request->request("fuwu",0);
        //附近有地铁站
        $data['sheshi'] = $this->request->request("sheshi",0);
        //老板不错
        $data['bossnice'] = $this->request->request("bossnice",0);
        //位置不错
        $data['position'] = $this->request->request("position",0);
        //图片
        $imgid = $this->request->request("imgid",0);
        if($imgid){
            $data['imgid'] = $imgid;
        }
        $now = time();
        $data['roomid'] = $rid;
        $data['uid'] = $uid;
        $data['ordernum'] = $order_number;
        $data['ctime'] = $now;
        $data['memo'] = $memo;


        Db::startTrans();
        $eff1 = db("comments")->where(['roomid'=>$rid,'uid'=>$uid,"ordernum"=>$order_number,"userdel"=>"0"])->find();
        if($eff1){
            $this->error("您已经评价过了，无需多次评价");
        }else{
            $inid = db("comments")->insertGetId($data);
            //更新房间平分
            $cavgpoint = db("comments")->where(['roomid'=>$rid,'userdel'=>'0'])->avg("goods");
            $cavgpoint = ceil($cavgpoint);
            if($cavgpoint < 1){
                $cavgpoint = 1;
            }elseif ($cavgpoint>5){
                $cavgpoint = 5;
            }
            $rup['h_point'] = $cavgpoint;
            $rup['updatetime'] = $now;
            //更新房间评论
            $eff2 = db("house")->where(['id'=>$rid])->update($rup);
            //酒店数据
            $rinfo = db("house")->where(['id'=>$rid])->field("id,h_id,h_point")->find();

            $avgpoint = db("house")->where(['h_id'=>$rinfo['h_id']])->avg("h_point");
            $avgpoint = ceil($avgpoint);
            if($avgpoint < 1){
                $avgpoint = 1;
            }elseif ($avgpoint>5){
                $avgpoint = 5;
            }
            $hup['h_point'] = $avgpoint;
            $hup['updatetime'] = $now;


            //更新酒店评分 酒店评分 = 所有房间评分的平分值
            $eff3 = db("hotels")->where(["hid"=>$rinfo['h_id']])->update($hup);

            //更新订单评价数据
            $orderup['comment'] = 1;
            $orderup['upd_time'] = $now;
            $eff4 = db("order")->where(['order_number'=>$order_number])->update($orderup);

            if($inid && $eff2 && $eff3 && $eff4){
                Db::commit();
                $this->success("评价成功");
            }else{
                Db::rollback();
                $this->error("评价失败");
            }

        }


    }

    //删除评论 //更新酒店评分
    public function delComment(){
        $cid = $this->request->request("cid");
        if(empty($cid)){
            $this->error("评论id不能为空");
        }
        $cinfo = db("comments")->where(['id'=>$cid])->field("id,roomid,goods")->find();
        $now =time();

        if($cinfo){
            Db::startTrans();
            $upd["userdel"] = 1;
            $upd["utime"] = $now;
            $eff3 = db("comments")->where(['id'=>$cid])->update($upd);
            $cavgpoint = db("comments")->where(['roomid'=>$cinfo['roomid'],'userdel'=>'0'])->avg("goods");
            $cavgpoint =ceil($cavgpoint);
            if($cavgpoint < 1){
                $cavgpoint = 1;
            }elseif ($cavgpoint>5){
                $cavgpoint = 5;
            }
            //房间数据
            $rinfo = db("house")->where(['id'=>$cinfo['roomid']])->field("id,h_id,h_point")->find();
            $rup['h_point'] = $cavgpoint;
            $rup['updatetime'] = $now;
            //更新房间评论
            $eff1 = db("house")->where(['id'=>$rinfo['id']])->update($rup);

            $avgpoint = db("house")->where(['h_id'=>$rinfo['h_id']])->avg("h_point");
            $avgpoint = ceil($avgpoint);
            if($avgpoint < 1){
                $avgpoint = 1;
            }elseif ($avgpoint>5){
                $avgpoint = 5;
            }
            $hup['h_point'] = $avgpoint;
            $hup['updatetime'] = $now;
            //更新酒店评分 酒店评分 = 所有房间评分的平分值
            $eff2 = db("hotels")->where(["hid"=>$rinfo['h_id']])->update($hup);
            if($eff1 && $eff2 && $eff3){
                Db::commit();
                $this->success("评论删除成功");
            }else{
                Db::rollback();
                $this->error("评论删除失败");
            }
        }else{
            $this->error("评论数据有误");
        }



    }

    //套餐（列表）
    //排序：0精选推荐 1离我最近 2销量最多 3价格优先 4即将下架
    public function actList(){
        $citycode = $this->request->request("citycode");
        $lng1 = $this->request->request("lng");
        $lat1 = $this->request->request("lat");
        $title = $this->request->request("title");
        $page = $this->request->request("page",1);
        $limit = $this->request->request("limit",4);
        $order = $this->request->request("order",0);

        if(empty($citycode)){
            $this->error('参数错误');
        }
        $now = date("Y-m-d",time());

        if($order == "0"){
            //精选推荐
            if($title){
                $count = db("activity")
                    ->where("status='normal'")
                    ->where(['h_areadid'=>$citycode])
                    ->where("`title` LIKE '%$title%'")
                    ->count();
                $list = db("activity")
                    ->where("status='normal'")
                    ->where(['h_areadid'=>$citycode])
                    ->where("`title` LIKE '%$title%'")
                    ->order("hot desc")
                    ->page($page,$limit)
                    ->field("id,img,title,hotelname,price,preprice,enddate,sell,hot")
                    ->select();
            }else{
                $count = db("activity")
                    ->where("status='normal'")
                    ->where(['h_areadid'=>$citycode])
                    ->count();
                $list = db("activity")
                    ->where("status='normal'")
                    ->where(['h_areadid'=>$citycode])
                    ->order("hot desc")
                    ->page($page,$limit)
                    ->field("id,img,title,hotelname,price,preprice,enddate,sell,hot")
                    ->select();
            }

        }elseif ($order == "1"){

            //1离我最近
            if($title){
                $count = db("activity")
                    ->where("status='normal'")
                    ->where(['h_areadid'=>$citycode])
                    ->where("`title` LIKE '%$title%'")
                    ->count();
                $list = db("activity")
                    ->where("status='normal'")
                    ->where(['h_areadid'=>$citycode])
                    ->where("`title` LIKE '%$title%'")
                    ->field("id,img,title,hotelname,price,preprice,enddate,sell,lng,lat,address")
                    ->select();
            }else{
                $count = db("activity")
                    ->where("status='normal'")
                    ->where(['h_areadid'=>$citycode])
                    ->count();
                $list = db("activity")
                    ->where("status='normal'")
                    ->where(['h_areadid'=>$citycode])
                    ->field("id,img,title,hotelname,price,preprice,enddate,sell,lng,lat,address")
                    ->select();
            }



            $templist = [];
            foreach ($list as $k=>&$v){
                $v["img"] = $this->mainhost.$v["img"];
                //判断是否到期
                $day = getDatediffeday($now,$v['enddate']);
                if($day <= 7 && $day >=0){
                    $v['text'] = "即将下架";
                }elseif($day < 0){
                    $v['text'] = "已下架";
                }else{
                    $v['text'] = "火热预定中";
                }
                // $v["address"] = $v["address"];
                $v["distance"] = getdistancekm($lng1,$lat1,$v["lng"],$v["lat"]);
                $sort[] = $v["distance"];
                unset($v['lng']);
                unset($v['lat']);
                $templist[$k] = $v;
            }

            array_multisort($sort,SORT_ASC,$templist);
            $offset = ($page-1)*$limit;
            $templist = array_slice($templist,$offset,$limit);

            $res["rowCount"] = $count;
            $res["pageSize"] = $limit;
            $res["pageIndex"] = $page;
            $res["pageCount"] = ceil($count/$limit);

            if($templist){
                $res["rowData"] = $templist;
                $this->success("success",$res);
            }else{
                $this->success("success",[]);
            }

        }elseif ($order == "2"){
            //2销量最多
            if($title){
                $count = db("activity")
                    ->where("status='normal'")
                    ->where(['h_areadid'=>$citycode])
                    ->where("`title` LIKE '%$title%'")
                    ->count();
                $list = db("activity")
                    ->where("status='normal'")
                    ->where(['h_areadid'=>$citycode])
                    ->where("`title` LIKE '%$title%'")
                    ->order("sell desc")
                    ->page($page,$limit)
                    ->field("id,img,title,hotelname,price,preprice,enddate,sell,hot")
                    ->select();
            }else{
                $count = db("activity")
                    ->where("status='normal'")
                    ->where(['h_areadid'=>$citycode])
                    ->count();
                $list = db("activity")
                    ->where("status='normal'")
                    ->where(['h_areadid'=>$citycode])
                    ->order("sell desc")
                    ->page($page,$limit)
                    ->field("id,img,title,hotelname,price,preprice,enddate,sell,hot")
                    ->select();
            }

        }elseif ($order == "3"){
            //3价格优先
            if($title){
                $count = db("activity")
                    ->where("status='normal'")
                    ->where(['h_areadid'=>$citycode])
                    ->where("`title` LIKE '%$title%'")
                    ->count();
                $list = db("activity")
                    ->where("status='normal'")
                    ->where(['h_areadid'=>$citycode])
                    ->where("`title` LIKE '%$title%'")
                    ->order("price asc")
                    ->page($page,$limit)
                    ->field("id,img,title,hotelname,price,preprice,enddate,sell,hot")
                    ->select();
            }else{
                $count = db("activity")
                    ->where("status='normal'")
                    ->where(['h_areadid'=>$citycode])
                    ->count();
                $list = db("activity")
                    ->where("status='normal'")
                    ->where(['h_areadid'=>$citycode])
                    ->order("price asc")
                    ->page($page,$limit)
                    ->field("id,img,title,hotelname,price,preprice,enddate,sell,hot")
                    ->select();
            }

        }elseif ($order == "4"){
            //4即将下架
            if($title){
                $count = db("activity")
                    ->where("status='normal'")
                    ->where(['h_areadid'=>$citycode])
                    ->where("`title` LIKE '%$title%'")
                    ->count();
                $list = db("activity")
                    ->where("status='normal'")
                    ->where(['h_areadid'=>$citycode])
                    ->where("`title` LIKE '%$title%'")
                    ->field("id,img,title,hotelname,price,preprice,enddate,sell")
                    ->select();
            }else{
                $count = db("activity")
                    ->where("status='normal'")
                    ->where(['h_areadid'=>$citycode])
                    ->count();
                $list = db("activity")
                    ->where("status='normal'")
                    ->where(['h_areadid'=>$citycode])
                    ->field("id,img,title,hotelname,price,preprice,enddate,sell")
                    ->select();
            }



            $templist = [];
            foreach ($list as $k=>&$v){
                $v["img"] = $this->mainhost.$v["img"];
                //判断是否到期
                $day = getDatediffeday($now,$v['enddate']);
                if($day <= 7 && $day >=0){
                    $v['text'] = "即将下架";
                    $v['status'] = 1;
                }elseif($day < 0){
                    $v['text'] = "已下架";
                    $v['status'] = 3;
                }else{
                    $v['text'] = "火热预定中";
                    $v['status'] = 2;
                }

                $sort[] = $v["status"];
                unset($v["status"]);
                $templist[$k] = $v;
            }

            array_multisort($sort,SORT_ASC,$templist);
            $offset = ($page-1)*$limit;
            $templist = array_slice($templist,$offset,$limit);

            $res["rowCount"] = $count;
            $res["pageSize"] = $limit;
            $res["pageIndex"] = $page;
            $res["pageCount"] = ceil($count/$limit);

            if($templist){
                $res["rowData"] = $templist;
                $this->success("success",$res);
            }else{
                $this->success("success",[]);
            }

        }




        $res["rowCount"] = $count;
        $res["pageSize"] = $limit;
        $res["pageIndex"] = $page;
        $res["pageCount"] = ceil($count/$limit);

        if($list){

            foreach ($list as &$v){
                $v['img'] = $this->mainhost.$v['img'];
                //判断是否到期
                $day = getDatediffeday($now,$v['enddate']);
                if($day <= 7 && $day >=0){
                    $v['text'] = "即将下架";
                }elseif($day < 0){
                    $v['text'] = "已下架";
                }else{
                    $v['text'] = "火热预定中";
                }
            }

            $res["rowData"] = $list;
            $this->success("success",$res);
        }else{
            $res["rowData"] = [];
            $this->success("success",[]);
        }


    }

    //活动详情
    public function actDetail(){

        $id = $this->request->request("id");
        if(empty($id)){
            $this->error('参数错误');
        }
        $info = db("activity")->where(['id'=>$id])->find();

        if($info){
            //处理图片
            if($info["imgs"]){
                $imgs = array();
                $imgarr = explode(",",$info["imgs"]);
                $len = count($imgarr);
                if($len > 1){
                    for ($i=0;$i<$len;$i++){
                        $imgs[$i] = $this->mainhost . $imgarr[$i];
                    }
                }else{
                    $imgs[0] = $this->mainhost . $info["imgs"];
                }
                $info["imglist"] = $imgs;
            }else{
                $info["imglist"] = [];
            }
            unset($info['imgs']);
            $info['fx_ewm'] = $this->mainhost.$info['fx_ewm'];

            //套餐
            $tclist = [];
            if($info['reactids']){
                $reactids = $info['reactids'];
                $tclist = db("activity")->field("id,title,price,label")->where("id in ($reactids)")->select();
                // 0需提前预约 1 不可退款 2无需换票
            }

            if($tclist){
                foreach ($tclist as &$vv){
                    if($vv['label'] != ""){
                        $arrdata = [];
                        $labarr = explode(",",$vv['label']);

                        if(in_array(0,$labarr)){
                            $arr['flag'] = 1;
                            $arr['title'] = "需提前预约";
                        }else{
                            $arr['flag'] = 0;
                            $arr['title'] = "需提前预约";
                        }
                        array_push($arrdata,$arr);
                        if(in_array(1,$labarr)){
                            $arr['flag'] = 1;
                            $arr['title'] = "不可退款";
                        }else{
                            $arr['flag'] = 0;
                            $arr['title'] = "不可退款";
                        }
                        array_push($arrdata,$arr);
                        if(in_array(2,$labarr)){
                            $arr['flag'] = 1;
                            $arr['title'] = "无需换票";
                        }else{
                            $arr['flag'] = 0;
                            $arr['title'] = "无需换票";
                        }
                        array_push($arrdata,$arr);

                        $vv['labelName'] = $arrdata;

                    }else{
                        $vv['labelName'] = [];
                    }
                    unset($vv['label']);


                }
                $info['relist'] = $tclist;
            }else{
                $info['relist'] = [];
            }

            unset($info['starttime']);
            unset($info['endtime']);
            unset($info['createtime']);
            unset($info['updatetime']);
            unset($info['img']);
            unset($info['lng']);
            unset($info['lat']);
            unset($info['fx_actimg']);
            unset($info['fx_posterone']);
            unset($info['h_areaid']);
            unset($info['h_areadid']);
            unset($info['hot']);
            unset($info['detailimgs']);
            unset($info['status']);
            $this->success("success",$info);
        }else{
            $this->error("数据错误");
        }

    }

    //购买套餐 生成支付数据 创建订单
    public function createAct(){
        $aid = $this->request->request("id");
        $uid = $this->request->request("uid");

        if(empty($aid) || empty($uid)){
            $this->error("用户参数错误");
        }

        $nowdate = date("Y-m-d",time());

        //获取套餐数据
        $info = db("activity")->where("id = $aid")->find();
        if($info['enddate']<$nowdate){
            $this->error("该套餐已经下架");
        }

        $userinfo = db("user")->where(['id'=>$uid])->find();
        $openid = $userinfo['openid'];

        //判断用户是否多次支付 （对同一个订单支付多次支付）
        $two['aid'] = $aid;
        $two['user_id'] = $uid;
        $two['pay_status'] = "0";
        $oldorder = db("orderactivity")->where($two)->find();

        if($oldorder){

            //获取支付数据
            $payres = $this->payActivity($openid,$oldorder['order_number'],$oldorder['price']);


            if($payres['code'] = 1){
                //微信支付套餐 回退微信费用  追加 日志
                $moneylog['type'] = 0;
                $moneylog['type2'] = 0;
                $moneylog['createtime'] = time();
                $moneylog['user_id'] = $uid;
                $moneylog['nickname'] = $userinfo['nickName'];
                $moneylog['memo'] = "微信支付-套餐消费";
                $moneylog['service_ids'] = $oldorder['order_number'];
                $moneylog['money'] =  $oldorder['price'];
                $moneylog['remark'] = "支付金额".$oldorder['price']."元，回退金额".$oldorder['price']."元";
                //添加消费日志
                $eff1 = db("user_money_log")->insert($moneylog);
                $this->success("success",$payres['data']);
            }else{
                $this->error($payres['data']);
            }


        }else{

            if(!$info){
                $this->error("活动数据错误");
            }
            try{
                $time = time();

                $orderData["order_number"] = "A".$aid."".date("YmdHis", time()) . rand(100000, 999999);
                $orderData["user_id"] = $uid;
                $orderData["aid"] = $aid;
                $orderData["price"] = $info["price"];
                $orderData["income"] = $info["price"];
                $orderData["preprice"] = $info["preprice"];
                $orderData["hotelname"] = $info["hotelname"];
                $orderData["title"] = $info["title"];
                $orderData["a_phone"] = $info["phone"];
                $orderData["user_phone"] = $userinfo["phone"];
                $orderData["order_phone"] = $userinfo["phone"];
                $orderData["order_name"] = $userinfo["nickName"];
                $orderData["add_time"] = $time;
                $orderData["pay_time"] = $time;
                $orderData["payend_time"] = $time + 30*60;
                $orderData["pay_status"] = "0";
                $orderData["activity_html"] = json_encode($info);
                $initid = db('orderactivity')->insertGetId($orderData);

                if($initid){
                    //获取支付数据
                    $payres = $this->payActivity($openid,$orderData["order_number"],$info["price"]);

                    if($payres['code'] = 1){

                        $up['prepay_id'] = $payres['data']['prepay_id'];
                        $up['upd_time'] = $time;


                        db('orderactivity')->where(['id'=>$initid])->update($up);

                        //微信支付套餐 回退微信费用  追加 日志
                        $moneylog['type'] = 0;
                        $moneylog['type2'] = 0;
                        $moneylog['createtime'] = time();
                        $moneylog['user_id'] = $uid;
                        $moneylog['nickname'] = $userinfo['nickName'];
                        $moneylog['memo'] = "微信支付-套餐消费";
                        $moneylog['service_ids'] = $orderData['order_number'];
                        $moneylog['money'] =  $orderData['price'];
                        $moneylog['remark'] = "支付金额".$orderData['price']."元，回退金额".$orderData['price']."元";
                        //添加消费日志
                        $eff1 = db("user_money_log")->insert($moneylog);
                        $this->success("success",$payres['data']);
                    }else{
                        $this->error($payres['data']);
                    }

                }else{
                    $this->error("订单生成失败");
                }

            }catch (\think\exception\PDOException $e){
                $this->error($e->getMessage());
            }

        }
    }

    //取消订单（套餐）暂时不考虑 取消订单收费问题
    public function cancelAct(){
        $order_number = $this->request->request("orderNumber");
        $uid = $this->request->request("uid");

        if(empty($order_number) || empty($uid)){
            $this->error("参数错误");
        }
        $where["user_id"] = $uid;
        $where["order_number"] =$order_number;
        //获取订单信息
        $info = db("orderactivity")->where($where)->find();
        $userinfo = db("user")->where(['id'=>$uid])->find();

        Db::startTrans();
        $now = time();
        $orderup['upd_time'] = $now;
        $orderup['cancel_time'] = $now;//取消时间
        $orderup["pay_status"] = "4";
        if($info){
            //根据订单状态判断操作
            if($info["pay_status"] == 0){ //未支付订单取消 退款额 为 总付款 （基础保障费 + 押金 + 房费）不用执行退款

                $eff1 = db("orderactivity")->where(['id'=>$info['id']])->update($orderup);
                if($eff1){
                    Db::commit();
                    $this->success("订单取消成功");
                }else{
                    DB::rollback();
                    $this->error("订单取消失败");
                }
            }elseif($info["pay_status"] == 1){
                //微信支付套餐 回退微信费用  追加 日志
                $moneylog['type'] = 0;
                $moneylog['type2'] = 1;
                $moneylog['createtime'] = $now;
                $moneylog['user_id'] = $uid;
                $moneylog['nickname'] = $userinfo['nickName'];
                $moneylog['memo'] = "微信支付-套餐费用回退";
                $moneylog['service_ids'] = $info['order_number'];
                $moneylog['money'] =  $info['price'];
                $moneylog['remark'] = "支付金额".$info['price']."元，回退金额".$info['price']."元";
                //添加消费日志
                $eff1 = db("user_money_log")->insert($moneylog);

                //准备退款数据
                //执行退款
                $refund_number = "refund_".date("YmdHis", time()) . rand(10000000, 99999999);
                $orderup["refund_number"] = $refund_number;
                $orderup["refund_status"] = 2;//申请退款中
                $refundRes = $this->submitDrawBackFun($info["price"],$info["price"] ,$info["order_number"],$refund_number,$info["transaction_id"],$info['user_id']);
                file_put_contents("refundactivity.json",var_export($refundRes,true).PHP_EOL,FILE_APPEND);
                //#todo 这里理论上还应该考虑 退款后 积分回退的逻辑，暂时先不考虑
                if ($refundRes['RETURN_CODE'] == 'SUCCESS' && $refundRes['RESULT_CODE'] == 'SUCCESS') {
                    file_put_contents("refundactivitysuc.json",var_export($refundRes,true));
                    //退款成功 修改订单状态
                    $orderup["refund_status"] = 3;
                    $eff2 = db("orderactivity")->where(["id"=>$info["id"]])->update($orderup);

                    if($eff1 && $eff2){
                        //取消成功后发送短信
                        /*//发送酒店
                        if($info["h_phone"] && $info["user_name"]){
                            sendmsgHCancel($info["h_phone"],$info["user_name"],$money);
                        }
                        //发送给用户
                        if($info["user_phone"] && $info["h_phone"]){
                            sendmsgUCancel($info["user_phone"],$money,$info["h_phone"]);
                        }*/

                        Db::commit();
                        $this->success("订单取消成功,自动退款，请注意查收");
                    }else{
                        Db::rollback();
                        $this->error("订单取消失败");
                    }

                }else{
                    file_put_contents("refundactivityerr.json",var_export($refundRes,true).PHP_EOL,FILE_APPEND);
                    Db::rollback();
                    $this->error("退款失败");
                }

            }elseif($info['pay_status'] == 3){
                $this->error("订单已完成，不能取消");
            }elseif($info['pay_status'] == 4){
                $this->error("您已经取消了订单！");
            }

        }else{
            $this->error("找不到订单");
        }

    }


    //套餐 立即预约 需要输入用户 电话 姓名 预约的时间
    public function actReserve(){
        $ordernumber = $this->request->request("orderNumber");
        $uid = $this->request->request("uid");
        $order_name = $this->request->request("name");
        $order_phone = $this->request->request("phone");
        //$time = $this->request->request("time");
        $time = time();

        if(empty($ordernumber) || empty($uid)){
            $this->error("参数错误");
        }

        if(empty($order_name) || empty($order_phone)){
            $this->error("预约人信息不能为空");
        }
        if(empty($time)){
            $this->error("预约时间不能为空");
        }

        $oinfo = db("orderactivity")->where(['order_number'=>$ordernumber,'user_id'=>$uid])->find();
        if($oinfo){

            if($oinfo['pay_status'] == "0"){
                $this->error("订单未支付");
            }
            //暂定完成状态有管理员操作
            if($oinfo['pay_status'] == "3"){
                $this->error("订单已完成");
            }
            if($oinfo['pay_status'] == "4"){
                $this->error("订单已取消");
            }

            if($oinfo['pay_status'] == "2"){
                $this->error("已预约，无需再次预约");
            }

            //添加预约信息
            if($oinfo['pay_status'] == "1"){
                $updata['pay_status'] = "2";
                $updata['order_name'] = $order_name;
                $updata['order_phone'] = $order_phone;
                $updata['yue_time'] = $time;
                $updata['upd_time'] = time();
                $eff = db("orderactivity")->where(['order_number'=>$ordernumber])->update($updata);
                if($eff){
                    $this->success("预约成功");
                }else{
                    $this->error("预约失败");
                }

            }

        }else{
            $this->error("订单数据有误");
        }

    }


    //套餐 取消预约 需要输入用户 电话 姓名
    public function actDelReserve(){
        $ordernumber = $this->request->request("orderNumber");
        $uid = $this->request->request("uid");
        if(empty($ordernumber) || empty($uid)){
            $this->error("参数错误");
        }

        $oinfo = db("orderactivity")->where(['order_number'=>$ordernumber,'user_id'=>$uid])->find();
        if($oinfo){

            if($oinfo['pay_status'] == "0"){
                $this->error("订单未支付");
            }
            //暂定完成状态有管理员操作
            if($oinfo['pay_status'] == "3"){
                $this->error("订单已完成");
            }
            if($oinfo['pay_status'] == "4"){
                $this->error("订单已取消");
            }
            if($oinfo['pay_status'] == "1"){
                $this->error("请先预约");
            }

            //取消预约信息
            if($oinfo['pay_status'] == "2"){
                $updata['pay_status'] = "1";
                $updata['yue_time'] = "";//取消预约 置空之前预约的时间
                $updata['upd_time'] = time();
                $eff = db("orderactivity")->where(['order_number'=>$ordernumber])->update($updata);
                if($eff){
                    $this->success("取消预约成功");
                }else{
                    $this->error("取消预约失败");
                }
            }

        }else{
            $this->error("订单数据有误");
        }

    }


    //套餐支付 生成支付的数据
    public function payActivity($openid,$ordernumber,$price){
        $res['code'] = 0;
        $res['data'] = [];
        if(!$openid || !$ordernumber || !$price){
            $res['data'] = "订单参数错误";
            return $res;
        }
        $price= $price * 100;  //真实需要支付的金额
        $out_trade_no = $ordernumber;
        $PrePay = WxPay::PrePayActivity($out_trade_no,$openid,$price);  //统一下单

        if($PrePay["return_code"]=="FAIL"){
            $res['data'] = "支付状态错误";
            return $res;
        }else{
            if(empty($PrePay["prepay_id"])){
                $res['data'] = "支付参数prepay_id错误";
                return $res;
            }else{
                $PrePayId=$PrePay["prepay_id"];  // 获取预支付id
                $PaySign=WxPay::getPaySign($PrePayId,$PrePay["nonce_str"]);
                $a= array("prepay_id"=>$PrePayId,"paySign"=>$PaySign["PaySign"],"nonce_str"=>$PrePay["nonce_str"],"timeStamp"=>$PaySign["timeStamp"],"order_no"=>$out_trade_no);
                $res['code'] = 1;
                $res['data'] = $a;
                return $res;
            }

        }
    }

    //活动支付回调
    public function wxxmlactivity(){
        $activityxml = file_get_contents("php://input");


        file_put_contents("testctivity.json",var_export($activityxml,true).PHP_EOL,FILE_APPEND);

        //将xml转化为json格式
        $jsonxml = json_encode(simplexml_load_string($activityxml, 'SimpleXMLElement', LIBXML_NOCDATA));
        //转成数组
        $result = json_decode($jsonxml, true);
        if($result){
            //如果成功返回了
            if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
                //写入回调日志
                file_put_contents("wxxmlactivity.json",var_export($result,true).PHP_EOL,FILE_APPEND);

                $ordernumber = $result['out_trade_no'];
                $up['pay_status'] = "1";
                $up['upd_time'] = time();
                $up['transaction_id'] = $result['transaction_id'];
                $up['sign'] = $result['sign'];
                $up['pay_time'] = time();
                db("orderactivity")->where(['order_number'=>$ordernumber])->update($up);
                echo 'success';die;
            }
        }



    }

    //套餐订单列表
    //状态 全部 0 未支付 1 已支付 2 已预定 3 已完成 4 已取消 5支付失败
    public function actOrderlist(){
        $uid = $this->request->request("uid");
        $status = $this->request->request("status","");
        $title = $this->request->request("title","");
        $page = $this->request->request("page",1);
        $limit = $this->request->request("limit",6);
        if(empty($uid)){
            $this->error("参数错误");
        }

        $where = "";
        if($status != ""){
            $where = " pay_status = '$status'";
        }

        $where1 = "";
        if($title != ""){
            $where1 = "`title` LIKE '%$title%'";
        }

        $count = db("orderactivity")
            ->where(['user_id'=>$uid])
            ->where($where)
            ->where($where1)
            ->count();

        $list = db("orderactivity")
            ->where(['user_id'=>$uid])
            ->where($where)
            ->where($where1)
            ->field("id,order_number,pay_status,price,activity_html,aid")
            ->page($page,$limit)
            ->order("id desc")
            ->select();

        if($list){
            foreach ($list as &$v){
                $html = json_decode($v['activity_html'],true);
                $v['img'] = $this->mainhost.$html['img'];
                $v['title'] = $html['title'];
                $v['hotelname'] = $html['hotelname'];
                $v['phone'] = $html['phone'];
                //订单状态
                if($v['pay_status'] == "0"){
                    $v['pay_statusText'] = "未支付";
                }elseif ($v['pay_status'] == 1){
                    $v['pay_statusText'] = "已支付";
                }elseif ($v['pay_status'] == 2){
                    $v['pay_statusText'] = "已预定";
                }elseif ($v['pay_status'] == 3){
                    $v['pay_statusText'] = "已完成";
                }elseif ($v['pay_status'] == 4){
                    $v['pay_statusText'] = "已取消";
                }else{
                    $v['pay_statusText'] = "支付失败";
                }
                unset($v['activity_html']);
            }

            $res["rowCount"] = $count;
            $res["pageSize"] = $limit;
            $res["pageIndex"] = $page;
            $res["pageCount"] = ceil($count/$limit);
            $res["rowData"] = $list;

            $this->success("success",$res);
        }else{
            $this->success("暂无记录",[]);
        }
    }

    //套餐订单详情
    public function actOrderDetail(){
        $orderNumber = $this->request->request("orderNumber");
        if(empty($orderNumber)){
            $this->error("订单号不能为空");
        }

        $oinfo = db("orderactivity")->where(['order_number'=>$orderNumber])->find();
        if($oinfo){
            //获取套餐详情数据
            $ainfo = db("activity")->where(['id'=>$oinfo['aid']])->field("id,title,hotelname,sell,stock,address,lng,lat,imgs,price,preprice,content,contentimg,read")->find();
            if(!$ainfo){
                $this->error("活动数据有误");
            }

            //处理图片
            if($ainfo["imgs"]){
                $imgs = array();
                $imgarr = explode(",",$ainfo["imgs"]);
                $len = count($imgarr);
                if($len > 1){
                    for ($i=0;$i<$len;$i++){
                        $imgs[$i] = $this->mainhost . $imgarr[$i];
                    }
                }else{
                    $imgs[0] = $this->mainhost . $ainfo["imgs"];
                }
                $ainfo["imglist"] = $imgs;
            }else{
                $ainfo["imglist"] = [];
            }
            unset($ainfo['imgs']);

            //登记信息
            $ainfo['ctime'] = date("Y-m-d H:i:s",$oinfo['add_time']);
            if($oinfo['yue_time'] != ""){
                $ainfo['paytype'] = 1;//已预约 前端显示取消预约
            }else{
                $ainfo['paytype'] = 0;//未预约 前端显示立即预约
            }
            $ainfo['paystatus'] = $oinfo['pay_status'];//订单状态
            $ainfo['ytime'] = $oinfo['yue_time'];//预约时间
            $ainfo['order_name'] = $oinfo['order_name'];//预约姓名
            $ainfo['order_phone'] = $oinfo['order_phone'];//预约电话

            $this->success("success",$ainfo);
        }else{
            $this->error("订单数据有误");
        }

    }
    //余额充值 支付
    public function reCharge(){

        $uid = $this->request->request("uid");
        $chongzhijine = $this->request->request("money");

        if(empty($uid) || empty($chongzhijine)){
            $this->error("参数错误");
        }

        $price=$chongzhijine * 100;  //真实需要支付的金额
        $out_trade_no = time().$this->makeCardPassword();  //充值订单号
        $userinfo = db("user")->where(['id'=>$uid])->field("openid")->find();

        //返回信息
        //返点比例
        $res2 = model('Config')->where("name='point'")->field("value")->find();
        $point = 0;
        if($res2){
            $point = $res2->toarray()["value"];
        }

        $fmoney = $chongzhijine + $chongzhijine * $point;

        if(!$userinfo){
            $this->error("用户信息错误");
        }
        if(!$userinfo['openid']){
            $this->error("用户openid错误");
        }
        $PrePay = WxPay::PrePaychongzhi($out_trade_no,$userinfo['openid'],$price);  //统一下单
        if($PrePay["return_code"]=="FAIL"){
            $this->error("return_code错误");
        }
        else{
            if(empty($PrePay["prepay_id"])){
                $this->error("prepay_id");

            }else{
                $PrePayId=$PrePay["prepay_id"];  // 获取预支付id
                $PaySign=WxPay::getPaySign($PrePayId,$PrePay["nonce_str"]);
                $a= array("prepay_id"=>$PrePayId,"paySign"=>$PaySign["PaySign"],"nonce_str"=>$PrePay["nonce_str"],"timeStamp"=>$PaySign["timeStamp"],"order_no"=>$out_trade_no,"money"=>$chongzhijine,"fmoney"=>$fmoney,"payType"=>'微信');
                $this->success('success',$a);
            }

        }
    }

    //余额充值 充值回调
    public function wxxmlchongzhi(){
        $testxml = file_get_contents("php://input");
        //将xml转化为json格式
        $jsonxml = json_encode(simplexml_load_string($testxml, 'SimpleXMLElement', LIBXML_NOCDATA));
        //转成数组
        $result = json_decode($jsonxml, true);
        if($result){
            //如果成功返回了
            if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
                //写入回调日志
                file_put_contents("wxxmlchongzhi.json",var_export($result,true).PHP_EOL,FILE_APPEND);
//               $this->notifyUrl($result['out_trade_no'],$result['sign'],$result['transaction_id'],$result["total_fee"]);
                $openid=$result['openid'];
//                $result['total_fee']=1000;
                $user=db('user')->where("openid = '$openid'")->find();

                $time=time();
                $data['money']=$result['total_fee']/100;
                $data['code1']=$result['transaction_id'];
                $data['code2']=$result['out_trade_no'];
                $data['openid']=$openid;
                $data['uid']=$user['id'];
                $data['nickname']=$user['nickName'];
                $data['ctime']=$time;
                //返点比例
                $res2 = model('Config')->where("name='point'")->field("value")->find();
                $point = 0;
                if($res2){
                    $point = $res2->toarray()["value"];
                }
                $fmoney =  $data['money'] +  $data['money'] * $point;
                $data['fmoney']=$fmoney;
                $data['point']=$point;


                Db::startTrans();
                //在充值表中插入一条记录
                $chongzhi = db('chongzhi')->insert($data);

                if($chongzhi){
                    $data2['user_id']=$user['id'];
                    $data2['nickname']=$user['nickName'];
                    $data2['money']=$result['total_fee']/100;
                    $data2['before']=$user['money'];
                    $data2['after']=$user['money'] + $result['total_fee']/100;
                    $data2['type']= 1;
                    $data2['type2']= 2; //购买
                    $data2['service_ids']=$result['transaction_id'];
                    $data2['createtime']=$time;
                    $data2['memo']='余额充值';
                    //在用户行为记录表中插入一条记录
                    $money_log = db('user_money_log')->insert($data2);
                    if($money_log){
                        //更新用户余额
                        $data3['money']=$result['total_fee']/100 + $user['money'];
                        $userupdate=db('user')->where("openid = '$openid'")->update($data3);
                        if($userupdate){
                            //充值返点记录
                            if($result['total_fee']/100 >= 1){
                                $data4=$data2;
                                $data4['memo']='充值余额赠送';
                                $data4['type']= 1;
                                $data4['type2']= 4;
                                $config=db('config')->where("id = 35")->find();
                                $bili=$config['value'];
                                $data4['money']= ($result['total_fee']/100)*$bili;
                                $data4['before']=  $data3['money'];
                                $data4['after']=  $data3['money']+ ($result['total_fee']/100)*$bili;

                                db('user_money_log')->insert($data4);
                                $data5['money'] = $data4['after'];
                                db('user')->where("openid = '$openid'")->update($data5);
                            }
                            Db::commit();
                            echo 'success';die;
                        }else{
                            Db::rollback();
                            echo 'success';die;
                        }
                    }else{
                        Db::rollback();
                        echo 'success';die;
                    }
                }else{
                    Db::rollback();
                    echo 'success';die;
                }
            }
        }



    }

    //我的小时卡
    public function myCard(){
        $uid = $this->request->request("uid");
        if(empty($uid)){
            $this->error("用户参数错误");
        }

        $list = db("user_card")->field("id,c_id,d_number,status,d_time,less_hours")->where(['uid'=>$uid])->select();

        if($list){
            foreach ($list as &$v){
                $cardinfo = db("card")->where(['id'=>$v['c_id']])->find();
                unset($v['c_id']);
                $v['cardname'] = $cardinfo['cardname'];
                $v['cardtype'] = $cardinfo['type'];
                $v['cardhours'] = $cardinfo['hours'];
                $v['canuse'] = "支持小时卡的房源";
                $v["d_time"] = date("Y-m-d H:i",strtotime($v['d_time']));
                //0未兑换 1已兑换没使用完 2已兑换并且消费完
                if($v['status'] == "0"){
                    $v['statustext'] = "激活小时卡";
                    $v['statusdoing'] = "请激活小时卡";
                }elseif ($v['status'] == "1"){
                    $v['statustext'] = "已激活，未使用完";
                    $v['statusdoing'] = "去使用";
                }else{
                    $v['statustext'] = "已消费完";
                    $v['statusdoing'] = "去购买";
                }
            }


            $this->success("success",$list);
        }else{
            $this->success("success",[]);
        }



    }

    //小时卡兑换
    public function exChange(){
        $uid = $this->request->request("uid");
        $duihuanma = $this->request->request("cardCode");
        if(empty($uid)){
            $this->error("uid不能为空");
        }
        if(empty($duihuanma)){
            $this->error("请输入兑换卷码");
        }

        //首先查这个兑换码对应的卡是哪个
        $m1=db('user_card')->where("d_number = '$duihuanma'")->find();

        if(!$m1){
            $this->error("兑换卷不存在");
        }else{
            //兑换码被使用了
            if($m1['uid']){
                $this->error("兑换卷码已被兑换");
            }

            //查看要兑换的这个卡  这个人名下有无未使用完的这个卡
            $m2=db('user_card')->where("uid = $uid and d_number = '$duihuanma' and status = '1'")->find();
            if($m2){
                $this->error("兑换卷码兑换过的小时卡，还未使用完，请勿再次兑换");
            }else{
                $data['d_time']=date('Y-m-d H:i:s',time());
                $data['uid']=$uid;
                $data['status']=1;
                $m3 = db('user_card')->where("d_number =  '$duihuanma'")->update($data);
                if($m3){
                    $this->success("兑换成功");
                }else{
                    $this->error("兑换失败");
                }
            }
        }

    }

    //小时卡兑换记录/购买记录
    public function exchangeList(){
        $uid = $this->request->request("uid");
        $type = $this->request->request("type",1);
        if(empty($uid)){
            $this->error("uid不能为空");
        }

        //type = 1 购买 0 兑换
        if($type == 1){
            $list = db("user_card")->where(['uid'=>$uid,'type'=>'1'])->field("id,c_id,d_time,type")->select();
        }else{
            $list = db("user_card")->where(['uid'=>$uid,'type'=>'0'])->field("id,c_id,d_time,type")->select();
        }


        if($list){
            foreach ($list as &$v){
                $cardinfo = db("card")->where(['id'=>$v['c_id']])->find();
                unset($v['c_id']);
                $v['cardname'] = $cardinfo['cardname'];
                $v['cardhours'] = $cardinfo['hours'];
                if($v['type'] == "1"){
                    $v['statustext'] = "购卡成功";
                }else{
                    $v['statustext'] = "兑换成功";
                }

                $v["d_time"] = date("m月d日 H:i:s",strtotime($v['d_time']));
            }
        }

        $this->success("success",$list);
    }

    //小时卡列表（平台发布的）
    public function cardList(){
        $list = db("card")->where(['status'=>'0'])->field("id,cardname,type,hours,price,introduce,jianjie,star,cattr")->select();

        if($list){
            foreach ($list as &$v){
                if($v['type'] == "0"){
                    $v['typetext'] = "尊享卡";
                    $v['typedo'] = "激活尊享卡";
                }elseif ($v['type'] == "1"){
                    $v['typetext'] = "至尊卡";
                    $v['typedo'] = "激活至尊卡";
                }else{
                    $v['typetext'] = "黄金卡";
                    $v['typedo'] = "激活黄金卡";
                }
                $v['canuse'] = "不限酒店";
                $v['endtime'] = "无限制";
                $v['dnumber'] = "***********";
                $arrdata = [];
                //0现金提现 1小时抵扣 2生日优惠 3积分好礼 4专属客房 5预定保留
                //  {"id": 1, "name": "现金提现", "icon": "/hourPackage/images/icon_01.png"},
                $labarr = explode(",",$v['cattr']);
                if(in_array(0,$labarr)){
                    $arr['id'] = 1;
                    $arr['name'] = "现金提现";
                    $arr['icon'] = $this->mainhost."/smallimg/xjtx.png";
                }else{
                    $arr['id'] = 1;
                    $arr['name'] = "现金提现";
                    $arr['icon'] = $this->mainhost."/smallimg/xjtx2.png";
                }
                array_push($arrdata,$arr);
                if(in_array(1,$labarr)){
                    $arr['id'] = 2;
                    $arr['name'] = "小时抵扣";
                    $arr['icon'] = $this->mainhost."/smallimg/xskdk.png";
                }else{
                    $arr['id'] = 2;
                    $arr['name'] = "小时抵扣";
                    $arr['icon'] = $this->mainhost."/smallimg/xskdk2.png";
                }
                array_push($arrdata,$arr);
                if(in_array(2,$labarr)){
                    $arr['id'] = 3;
                    $arr['name'] = "生日优惠";
                    $arr['icon'] = $this->mainhost."/smallimg/sryh.png";
                }else{
                    $arr['id'] = 3;
                    $arr['name'] = "生日优惠";
                    $arr['icon'] = $this->mainhost."/smallimg/sryh2.png";
                }
                array_push($arrdata,$arr);
                if(in_array(3,$labarr)){
                    $arr['id'] = 4;
                    $arr['name'] = "积分好礼";
                    $arr['icon'] = $this->mainhost."/smallimg/jfhl.png";
                }else{
                    $arr['id'] = 4;
                    $arr['name'] = "积分好礼";
                    $arr['icon'] = $this->mainhost."/smallimg/jfhl2.png";
                }
                array_push($arrdata,$arr);
                if(in_array(4,$labarr)){
                    $arr['id'] = 5;
                    $arr['name'] = "专属客房";
                    $arr['icon'] = $this->mainhost."/smallimg/zskf.png";
                }else{
                    $arr['id'] = 5;
                    $arr['name'] = "专属客房";
                    $arr['icon'] = $this->mainhost."/smallimg/zskf2.png";
                }
                array_push($arrdata,$arr);
                if(in_array(5,$labarr)){
                    $arr['id'] = 6;
                    $arr['name'] = "预定保留";
                    $arr['icon'] = $this->mainhost."/smallimg/ydbl.png";
                }else{
                    $arr['id'] = 6;
                    $arr['name'] = "预定保留";
                    $arr['icon'] = $this->mainhost."/smallimg/ydbl2.png";
                }
                array_push($arrdata,$arr);
                $v['cattr'] = $arrdata;
                //卡片星数
                $cardstar = [];
                for($i= 0;$i<$v['star'];$i++){
                    array_push($cardstar,"true");
                }
                unset($v['star']);
                $v['cardstar'] = $cardstar;
                $v['userstar'] = 4;

            }
            $res['rowdata'] = $list;
        }
        $res['buyread'] = "云渚分时住购卡页会员卡的出现就是为了让会员顾客享受折扣优惠和预储值消费,而会员卡管理系統则是用于管理这些会员卡,帮助计算会员优惠和消费信息的会员系统。那么这个会员卡系统从给会员顾客办卡到实时使用,是怎样的管理流程呢?首先需要创建卡种类,对卡的名称、面值、有效期及各种权益进行配置,完成配置后生成会员卡商品。对折扣和权益多补充一句,不同省份、地区因为物价水平不同,相同等级的卡可能会存在不同权益的情況,需要提前考虑到。例如,一款咖啡在上海售价是100元,在拉萨的售价可能是80元,是否同样都享受8折就需要从业务上进行考虑了。";

        $this->success("success",$res);

    }

    //小时卡详情页面（会员页面）
    public function cardDetail(){
        $id = $this->request->request("cid");
        if(empty($id)){
            $this->error("cid参数错误");
        }

        $cinfo = db("card")->where(['id'=>$id])->find();
        if($cinfo){
            if($cinfo['status'] == "1"){
                $this->error("该小时卡已经下架,请选择其他购买");
            }
            unset($cinfo['status']);
            if($cinfo['type'] == ""){
                $cinfo['typetext'] = "尊享卡";
            }elseif ($cinfo['type'] == "1"){
                $cinfo['typetext'] = "至尊卡";
            }else{
                $cinfo['typetext'] = "黄金卡";
            }
            $cinfo['endtime'] = "无限制";
            $cinfo['dnumber'] = "***********";
            unset($cinfo['type']);
            unset($cinfo['image']);
            unset($cinfo['ctime']);



            $this->success("success",$cinfo);
        }else{
            $this->error("数据错误");
        }




    }

    //小时卡购买
    public function bugCard(){
        $uid = $this->request->request("uid");
        $cardid = $this->request->request("cid");
        if(empty($uid) || empty($cardid)){
            $this->error("参数错误");
        }
        //获取订单金额数据
        $info = db("card")->where("id = $cardid")->find();
        if(!$info){
            $this->error("小时卡数据有误");
        }
        if($info['status'] == 1){
            $this->error("该小时卡已下架");
        }
        $uinfo = db("user")->where(['id'=>$uid])->find();
        if(!$uinfo){
            $this->error("用户信息不存在");
        }
        if(!$uinfo['openid']){
            $this->error("用户openid不存在");
        }

        $price=$info["price"] * 100;  //真实需要支付的金额
        $out_trade_no = $cardid.'_'.time().$this->makeCardPassword();  //订单号就是卡号
        $PrePay = WxPay::PrePaycard($out_trade_no,$uinfo['openid'],$price);  //统一下单
        if($PrePay["return_code"]=="FAIL"){
            $this->error("微信return_code错误");
        }
        else{
            if(empty($PrePay["prepay_id"])){
                $this->error("微信prepay_id错误");
            }else{
                $PrePayId=$PrePay["prepay_id"];  // 获取预支付id
                $PaySign=WxPay::getPaySign($PrePayId,$PrePay["nonce_str"]);
                $a= array("prepay_id"=>$PrePayId,"paySign"=>$PaySign["PaySign"],"nonce_str"=>$PrePay["nonce_str"],"timeStamp"=>$PaySign["timeStamp"],"order_no"=>$out_trade_no);
                $this->success('success',$a);
            }

        }
    }

    //小时卡购买成功后的回调
    public function wxxmlcard(){
        $testxml = file_get_contents("php://input");
        //将xml转化为json格式
        $jsonxml = json_encode(simplexml_load_string($testxml, 'SimpleXMLElement', LIBXML_NOCDATA));
        //转成数组
        $result = json_decode($jsonxml, true);
        if($result){
            db::startTrans();
            $now = time();
            //如果成功返回了
            if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
                //写入回调日志
                file_put_contents("wxxmlbanka.json",var_export($result,true).PHP_EOL,FILE_APPEND);
                $openid=$result['openid'];
                $var=explode("_",$result['out_trade_no']);
                $cardid = $var[0];
                $time = date('Y-m-d H:i:s',$now);
                $less=db('card')->where("id = $cardid")->find();
                $user=db('user')->where("openid = '$openid'")->find();
                $nowhour = $user['hours'];//当前小时数

                //添加购买小时卡数据
                $uid = $user['id'];
                $data['c_id']=$cardid;
                $data['less_hours']=$less['hours'];
                $data['uid']=$uid;
                $data['nickname']=$user['nickName'];
                $data['order_number']=$result['out_trade_no'];
                $data['transaction_id']=$result['transaction_id'];
                $data['d_number']=$uid.$this->generate_password();
                $data['status']='1';
                $data['c_hours']=$less['hours'];
                $data['c_price']=$less['price'];
                $data['d_time']=$time;
                $data['c_time']=$time;
                $data['type']=1;
                $eff1 = db('user_card')->insert($data);

                //更新用户小时卡
                $userup['hours'] = $nowhour + $less['hours'];
                $userup['updatetime'] = $now;
                $eff2 = db("user")->where(['id'=>$uid])->update($userup);

                //追加user_money_log表
                $moneylog['user_id'] = $uid;
                $moneylog['nickname'] = $user['nickName'];
                $moneylog['money'] = $less['hours'];
                $moneylog['before'] = $nowhour;//购买前小时数
                $moneylog['after'] = $nowhour + $less['hours'];
                $moneylog['memo'] = "支付".$less['price']."元-购买小时卡";
                $moneylog['createtime'] = $now;
                $moneylog['type'] = 2;
                $moneylog['type2'] = 3;
                $moneylog['extra'] = $less['price'];
                $moneylog['service_ids'] = $result['out_trade_no'];
                $moneylog['remark'] = "微信支付购买小时卡，支付".$less['price']."元，购买小时数".$less['hours'];
                $eff3 = db("user_money_log")->insertGetId($moneylog);

                if($eff1 && $eff2 && $eff3){
                    Db::commit();
                    echo 'success';die;
                }else{
                    Db::rollback();
                }
            }

        }
    }

    function generate_password( $length = 9 ) {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $password = '';
        for ( $i = 0; $i < $length; $i++ )
        {
            $password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
        }
        return $password;
    }

    /**
     * @return array
     */
    public function getBeforeActionList()
    {
        return $this->beforeActionList;
    }


    //内部使用方法
    //封装退款方法 复制后台退款代码
    //退款开始
    public function submitDrawBackFun($all_money,$return_money,$out_trade_no,$refund_number,$transaction_id,$user_id){
        //通过微信api进行退款流程
        $nonce_str = WxPay::str_rand();//随机32位字符串
        $total_fee = $all_money * 100;//总金额，单位：分
        //$total_fee= 0.01 * 100;//测试 一分钱
        //$refund_fee= 0.01 * 100;//测试 一分钱
        $refund_fee = $return_money * 100;//退款金额，单位：分
        $parma = array(
            'appid'=> WxPay::appid,
            'mch_id'=> WxPay::mch_id,
            'nonce_str'=> $nonce_str,
            'out_trade_no'=> $out_trade_no,//小程序自定义订单号，支付时后台生成
            'out_refund_no'=> $refund_number,
            'total_fee'=> $total_fee,
            'refund_fee'=> $refund_fee,
            'transaction_id' => $transaction_id,//小程序平台订单号，微信平台生成
        );
        $KEY = WxPay::key;//小程序支付秘钥
        $parma['sign'] = $this->getSign($parma, $KEY);
        $post_xml = $this->arrayToXml($parma);//把参数转化成xml格式
        //向微信平台api发送退款参数
        $xmlresult = $this->postXmlSSLCurl($post_xml,'https://api.mch.weixin.qq.com/secapi/pay/refund');
        //解析返回的参数
        $array = $this->xml2array($xmlresult);
        //两个success表示退款成功，无需使用回调，在此进行逻辑处理即可
        return $array;

    }
    //获取xml里面数据，转换成array
    private function xml2array($xml)
    {
        $p = xml_parser_create();
        xml_parse_into_struct($p, $xml, $vals, $index);
        xml_parser_free($p);
        $data = [];

        foreach ($index as $key => $value) {
            if ($key == 'xml' || $key == 'XML') continue;
            $tag = $vals[$value[0]]['tag'];
            $value = $vals[$value[0]]['value'];
            $data[$tag] = $value;
        }
        return $data;
    }
    protected function getSign($params, $key)
    {
        ksort($params, SORT_STRING);
        $unSignParaString = $this->formatQueryParaMap($params, false);
        return $signStr = strtoupper(md5($unSignParaString . "&key=" . $key));
    }
    protected function formatQueryParaMap($paraMap, $urlEncode = false)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if (null != $v && "null" != $v) {
                if ($urlEncode) {
                    $v = urlencode($v);
                }
                $buff .= $k . "=" . $v . "&";
            }
        }
        $reqPar = '';
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }
    //数组转字符串方法
    protected function arrayToXml($arr){
        $xml = "<xml>";
        foreach ($arr as $key=>$val)
        {

            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }
    //需要使用证书的请求
    function postXmlSSLCurl($xml,$url,$second=30)
    {
        //使用的啊里云宝塔，存放证书路径，放在public中，新建cert

        $cert = '/www/wwwroot/minsuceshi/public/cert/apiclient_cert.pem';
        $key = '/www/wwwroot/minsuceshi/public/cert/apiclient_key.pem';
//        $cert = 'C:\Users\Administrator\Desktop\1602911873_20201017_cert/apiclient_cert.pem';
//         $key = 'C:\Users\Administrator\Desktop\1602911873_20201017_cert/apiclient_key.pem';
        $ch = curl_init();
        //超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        //这里设置代理，如果有的话
        //curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //设置证书
        //使用证书：cert 与 key 分别属于两个.pem文件
        //默认格式为PEM，可以注释,使用getcwd()方法，拼接证书的绝对路径
        curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
        curl_setopt($ch, CURLOPT_SSLCERT,$cert);

        //默认格式为PEM，可以注释,使用getcwd()方法，拼接证书的绝对路径
        curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
        curl_setopt($ch, CURLOPT_SSLKEY,$key);

        //post提交方式
        curl_setopt($ch, CURLOPT_POST, true);

        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);

        $data = curl_exec($ch);

//        p($data);die;
        //返回结果
        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            echo "curl出错，错误码:$error" . "<br>";
            curl_close($ch);
            return false;
        }
    }

    //充值订单生成
    function makeCardPassword() {
        $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $rand = $code[rand(0,25)]
            .strtoupper(dechex(date('m')))
            .date('d').substr(time(),-5)
            .substr(microtime(),2,5)
            .sprintf('%02d',rand(0,99));
        for(
            $a = md5( $rand, true ),
            $s = '0123456789ABCDEFGHIJKLMNOPQRSTUV',
            $d = '',
            $f = 0;
            $f < 8;
            $g = ord( $a[ $f ] ),
            $d .= $s[ ( $g ^ ord( $a[ $f + 8 ] ) ) - $g & 0x1F ],
            $f++
        );
        return  $d;
    }

    //首页轮播图
    public function getImglist(){
        $list = db("imagelist")->field("id,image,url")->where(['status'=>'normal'])->order("hot desc,id desc")->select();
        foreach ($list as &$v){
            $v['image'] = $this->mainhost.$v['image'];
        }
        $this->success("succes",$list);
    }























}
